vb.net - 如何在数据模板中设置组合框的 selectedvalue 和 itemssource

标签 vb.net mvvm combobox datacontext selectedvalue

这个问题与 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/

相关文章:

c# - 为什么 [Enum].Parse 有一个 ignoreCase 参数?

javascript - 有没有一种方法可以初始化一个保留初始 HTML 的 Vue 对象

wpf - wpf中的复选框禁用和启用

C# WinForms ComboBox - 仅从对象中选择值

JavaFX 组合框图像

c# - XML反序列化成不同的类?

c# - 将字符串转换为 TitleCase、SentenceCase、UpperCase 和 LowerCase,但如果单词在 "quotation marks"内则忽略大小写

xml - 从 xml 文件的 vb.net 十六进制扫描

model-view-controller - MVC 中的 M 与 MVVM 中的不同吗?

c++ - 将工具提示添加到 ComboBoxEx 失败