4est 4est - 13 days ago 7
C# Question

Binding DataGrid wth ComboBox (PropertyChanged, WPF, Binding)

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

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


cs:

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">
<DataGrid.Columns>
<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"/>
</DataGrid.Columns>
</DataGrid>


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

mm8 mm8
Answer

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">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Auto Name" Binding="{Binding AutoName, UpdateSourceTrigger=PropertyChanged}" Width="100"/>
        <DataGridTextColumn Header="Color" Binding="{Binding Color, UpdateSourceTrigger=PropertyChanged}" Width="100"/>
    </DataGrid.Columns>
</DataGrid>