WPF DataGrid ComboBox SelectedItem Property Setter

和自甴很熟 提交于 2021-02-11 12:58:49

问题


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>

The DataContext I bind to (ListCustomerCollection) is a List object

  List<Customer> 

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");
    }
}

So how do I writethe XAML to set the above property with the SelectedItem?


回答1:


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}}"/>


来源:https://stackoverflow.com/questions/23091221/wpf-datagrid-combobox-selecteditem-property-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!