简体   繁体   中英

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?

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>

You need to add an event in combobox:

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

And in the selectionInComboboxChanged you can get the selected cobobox item and then add it to the mydata.test_views list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM