I have a daetagrid and a combobox and a textbox in a window in wpf.
in xmal:
<TextBox x:Name="txtCameraName"/>
<ComboBox x:Name="cmbCameraType" SelectedValuePath="Camera_Type" IsEditable="True" IsReadOnly="True" Text="Please select...">
<ComboBoxItem>IP</ComboBoxItem>
<ComboBoxItem>webcam</ComboBoxItem>
<ComboBoxItem>analogue</ComboBoxItem>
</ComboBox>
<DataGrid x:Name="mydgv" SelectionChanged="dgvAddPersonTab_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Camera_Name}" Width="80" />
<DataGridTextColumn Binding="{Binding Camera_Type}" Width="80" />
</DataGrid.Columns>
I get all fields of a table named mytbl and show them in datagrid with this code:
private void window_Loaded(object sender, RoutedEventArgs e)
{
var q= from j in CamDB.mytbl select q;
mydgv.ItemsSource = q.ToList();
}
and mytbl
is a table that it has two field : Camera_Name
, Camera_Type
. Now I want to show value of Camera_Name
in textbox and value of Camera_Type
in combo when I select a row of datagrid. I read this link and I tried with following code but it worked about textbox while it didn't work about combo.
private void mydgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var AllFields = mydgv.SelectedItem;
txtCameraName.Text = AllFields.GetType().GetProperty("Camera_Name").GetValue(AllFields, null).ToString();
cmbCameraType.SelectedValue = AllFields.GetType().GetProperty("Camera_Type").GetValue(AllFields, null);
}
我用下面的代码,它的工作原理:
cmbCameraType.Text = AllFields.GetType().GetProperty("Camera_Type").GetValue(AllFields, null).ToString();
Have you tried binding?
Try adding these to the TextBox and ComboBox in xaml:
<TextBox Text="{Binding ElementName=mydgv,Path=SelectedItem.Camera_Name" />
<ComboBox Text="{Binding ElementName=mydgv,Path=SelectedItem.Camera_Type" />
Other things were omitted.
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.