在项目源之外绑定 ViewModel 字段

Spo*_*ior 1 xamarin xamarin.forms

嗨,我有一个绑定联系人列表的 ItemSource

<ListView  x:Name="contactsListView" ItemsSource="{Binding contacts}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Image Source="{Binding Should be to my View Model instead of Contacts}"></Image>
                            <Label Text="{Binding FullName}"></Label>
                        </StackLayout>

                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

全名绑定工作正常。我的问题是图像源不包含在联系人模型中,所以我需要从我的视图模型中检索它我该怎么做?

查看模型

    public class ContactsViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Contact> contacts { get; set; }
    private string _contactImage;

    public string ContactImage
    {
        get => _contactImage; set
        {
            _contactImage = value;
            OnPropertyChanged("ContactImage");
        }
    }

    public ContactsViewModel(List<Contact> _contacts)
    {
        contacts = new ObservableCollection<Contact>(_contacts);
        ContactImage = "arrow.png";



    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

代码隐藏视图

    public partial class ContactListPage : TabbedPage
{
    public ContactsViewModel vm;
    public ContactListPage (List<Contact> _contacts)
    {
        vm = new ContactsViewModel(_contacts);
        BindingContext = vm;
        InitializeComponent();

    }
}
Run Code Online (Sandbox Code Playgroud)

Ger*_*uis 5

这是因为ListView项目内的范围与更高的级别不同。要克服这个问题,请创建对父控件的引用。我看到你已经命名了 your ListView,所以我们可以使用它。

像这样做: <Image Source="{Binding Path=BindingContext.ContactImage, Source={x:Reference contactsListView}}"></Image>