这个问题与 MVVM 项目结构有关。
为了在 ListView 中显示数据,我使用 DataTemplate。 ListView 的 ItemsSource 是 ObservableCollection(of Person)。到目前为止没有什么特别的。
但是在 DataTemplate 中,我想在 ComboBox 中显示每个 Person 的 State 属性,其中显示实际值,并且用户可以选择另一个 State。
State 来自于 States,即 ObservableCollection(of State)。
为了显示所有状态,我需要将 DataContext 绑定(bind)到 ViewModel 的“顶层”。但是我如何再次归结为个人,这在 DataTemplate 中显示?还是我需要另一种方法来解决这个问题?
在 XAML 我有这个:
<ComboBox DataContext="{Binding DataContext, ElementName=pageRoot}" ItemsSource="{Binding States}" DisplayMemberPath="Description" SelectedValue="{Binding ??????}" SelectedValuePath="ID" />
我的问题是:我需要设置什么才能正确绑定(bind) SelectedValue 以便它在组合框的文本字段中显示每个人的实际状态?
最佳答案
知道了!
对于 ComboBox 的 ItemsSource,我需要 DataContext 层次结构的“更高”级别。我只需要将 ItemsSource 绑定(bind)到该级别,而不是将整个 ComboBox 绑定(bind)到该 DataContext。
更正后的代码现在看起来像这样:
<ComboBox
ItemsSource="{Binding DataContext.States, ElementName=pageRoot}"
DisplayMemberPath="Description"
SelectedValue="{Binding State.ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="ID"
反复试验成功了! :-)
关于vb.net - 如何在数据模板中设置组合框的 selectedvalue 和 itemssource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038658/