Xamarin.Forms-选择器选定的项目绑定未响应



我正在用xamarin.forms中的picker字段进行简单的MVVM绑定。我遵循本指南Xamarin指南设置选择器的绑定

所以我制作了一个模型:

public class Operation
{
    public int Number { get; set; }
    public string Name { get; set; }
}

ViewModel:

private List<Operation> _operations;
public List<Operation> Operations
{
    get { return _operations; }
    set
    {
        _operations = value;
        OnPropertyChanged();
    }
}

和查看:

<Picker 
    ItemsSource="{Binding Operations}"
    ItemDisplayBinding="{Binding Number}"
    SelectedItem = "{Binding SelectedOperation}"/>
<Entry x:Name="HelpEntry"
       Text="{Binding SelectedOperation.Name}" />

在选择器列表中的项目显示正确,但是当我选择一个项目编号时,未显示条目内的绑定。

ouestion是,我在做什么错?


顺便说一句。我这样做是因为我需要使用helpentry.text将所选的Operation's Name作为变量。这不是最聪明的方法,您有更好的想法吗?

任何帮助都会非常感谢。

您的ViewModel还应包含SelectedOperation属性,该属性还应在其设置中调用OnPropertyChanged方法。

还应该考虑在查看模型中使用ObservableCollection而不是List

确保您的ViewModel实现InotifyPropertychanged接口。轻松执行此操作的方法是创建一个实现接口,然后从此基类继承所有混凝土视图模型类的baseviewModel。

 public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
public class MainPageVM : ViewModelBase
{...}

最新更新