4est 4est - 6 months ago 40
C# Question

Binding DataGrid wth ComboBox (PropertyChanged, WPF, Binding)

On UserControl into xmal have ComboBox filled "Id" items:

<ComboBox x:Name="cmbId" DisplayMemberPath="Id"/>


cmbId.ItemsSource = (from q in mydata.test_views
select q).ToList();

I'm trying to fill data into DataGrid:

<DataGrid x:Name="UGrid" AutoGenerateColumns="False">
<DataGridTextColumn Header="Auto Name" Binding="{Binding SelectedItem.AutoName, UpdateSourceTrigger=PropertyChanged, ElementName=cmbId}" Width="100"/>
<DataGridTextColumn Header="Color" Binding="{Binding SelectedItem.Color, UpdateSourceTrigger=PropertyChanged, ElementName=cmbId}" Width="100"/>

How to display data "Auto Name & Color" value after user select item on ComboBox?

mm8 mm8
Answer Source

The ItemsSource of a DataGrid is supposed to be set to an IEnumerable<T>. If you only want to display a single item in the DataGrid, you could handle the SelectionChanged event for the ComboBox and set the ItemsSource property of the DataGrid to a List<T> that contains the selected item in the ComboBox:

private void cmbId_SelectionChanged(object sender, SelectionChangedEventArgs e)
    UGrid.ItemsSource = new List<YourEntityType> { cmbId.SelectedItem as YourEntityType };

<DataGrid x:Name="UGrid" AutoGenerateColumns="False">
        <DataGridTextColumn Header="Auto Name" Binding="{Binding AutoName, UpdateSourceTrigger=PropertyChanged}" Width="100"/>
        <DataGridTextColumn Header="Color" Binding="{Binding Color, UpdateSourceTrigger=PropertyChanged}" Width="100"/>