我正在寻找一个如何在WPF DataGrid中的组合框内使用SelectedItem属性的示例,我有
<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对象
List<Customer>
所以我设置的ViewModel属性中的属性是
private Customer m_Customer = null;
public Customer Customer
{
get { return m_Customer; }
set
{
m_Customer = value;
OnPropertyChanged("Customer");
}
}
那么如何写XAML以使用SelectedItem设置上述属性?
答案 0 :(得分:1)
如果属性位于窗口的ViewModel中,则必须像使用ItemsSource一样获取窗口的DataContext。
<Setter Property="SelectedItem"
Value="{Binding DataContext.Customer,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}"/>