WPF DataGrid ComboBox SelectedItem属性设置器 [英] WPF DataGrid ComboBox SelectedItem Property Setter
本文介绍了WPF DataGrid ComboBox SelectedItem属性设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个示例,该示例如何在WPF DataGrid中的组合框内使用SelectedItem属性
I am looking for an example of how to use the SelectedItem property inside a combobox in a WPF DataGrid, I have
<DataGridComboBoxColumn SelectedValueBinding="{Binding CID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="CID"
Header="CID"
Width="70">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.ListCustomerCollection,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
<Setter Property="DisplayMemberPath" Value="Name"/>
<Setter Property="SelectedItem" Value="{Binding DataContext.Customer, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"></Setter>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding DataContext.ListCustomerCollection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
<Setter Property="DisplayMemberPath" Value="Name"/>
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Setter Property="SelectedItem" Value="{Binding DataContext.Customer, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"></Setter>
</Style>
</DataGridComboBoxColumn.ElementStyle>
我绑定到(ListCustomerCollection)的DataContext是一个List对象
The DataContext I bind to (ListCustomerCollection) is a List object
List<Customer>
所以我在ViewModel属性中设置的属性是
so the property in the ViewModel property I have set is
private Customer m_Customer = null;
public Customer Customer
{
get { return m_Customer; }
set
{
m_Customer = value;
OnPropertyChanged("Customer");
}
}
那么我该如何编写XAML以使用SelectedItem设置上述属性?
So how do I writethe XAML to set the above property with the SelectedItem?
推荐答案
如果属性位于窗口的ViewModel中,则必须像对ItemsSource一样获取窗口的DataContext.
If property resides in window's ViewModel, you have to get window's DataContext like you did for ItemsSource.
<Setter Property="SelectedItem"
Value="{Binding DataContext.Customer,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}"/>
这篇关于WPF DataGrid ComboBox SelectedItem属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文