将视图模型绑定到ComboBox

时间:2017-06-07 13:55:53

标签: xaml data-binding combobox uwp

我正在制作一个UWP应用,我已将ObservableCollection<EduRole>绑定到ComboBox。我可以看到ComboBox中填充的项目。但是我还需要设置它SelectedItem属性,这是我无法工作的。

XAML:

<ComboBox Name="EducationalLevelComboBoxUpdate"
    ItemsSource="{x:Bind EduRoleList, Mode=OneWay}"

    <!--IS THIS OKAY?-->
    SelectedItem="{x:Bind Path=User.EduRole.Read, Mode=OneWay}"

    PlaceholderText="Select educational role">
    <ComboBox.ItemTemplate>
        <DataTemplate x:DataType="viewModels:EduRoleViewModel">
            <TextBlock Text="{x:Bind Read}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

来源:

  private ObservableCollection<EduRoleViewModel> EduRoleList { get; set; } = new ObservableCollection<EduRoleViewModel>();

视图模型:

public class EduRoleViewModel
{
    public string Key { get; set; }
    public string Read { get; set; }
}

User是一个名为UserViewModel的类的对象,该类具有EduRoleViewModel类型属性,该类是:

class UserViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private EduRoleViewModel _eduRole;
    public EduRoleViewModel EduRole
    {
        get { return _eduRole; }
        set
        {
            _eduRole = value;
            this.OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {            
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

我希望Read EduRole属性的UserViewModel属性为SelectedItem

ComboBox

0 个答案:

没有答案