【问题标题】:WPF: Problem with binding values to ComboBox inside GridViewColumnWPF:将值绑定到 GridViewColumn 内的 ComboBox 出现问题
【发布时间】:2010-09-22 04:33:25
【问题描述】:
My Views dataContext 绑定到具有两个 observableCollections 成员的presentationModel。在视图中,我有一个 ListView,ItemSource 绑定到的是第一个 observableCollection。在 LilstViews 列之一中,我想在我的presentationModel 中显示第二个可观察集合中的值。我不知道如何将 observableCollection 中的值获取到我的组合框中。有谁知道如何解决这个问题?
【问题讨论】:
标签:
wpf
data-binding
combobox
gridviewcolumn
【解决方案1】:
您需要做的第一件事是创建一个包含 ComboBox 的数据模板,在这种情况下,我已将 ItemsSource 绑定到主机窗口上的 DependencyProperty。这包含表示模型,它有一个名为 ComboSource 的属性。 SelectedValue 已通过 ListViewItem 的 DataContext 绑定到保存所选值的属性。
<ListView.Resources>
<DataTemplate x:Key="comboBoxTemplate">
<ComboBox
ItemsSource="{Binding
Path=ModelData.ComboSource,
RelativeSource={RelativeSource AncestorType=Window}}"
SelectedValue="{Binding
Path=DataContext.Selection,
RelativeSource={RelativeSource AncestorType=ListViewItem}}"
DisplayMemberPath="Item"
SelectedValuePath="Id"
/>
</DataTemplate>
</ListView.Resources>
然后你需要从 GridViewColumn 上的 CellTemplate 中引用它
<GridViewColumn
Header="Selection"
Width="160"
CellTemplate="{StaticResource comboBoxTemplate}"
/>