首先,定义一个DataTable,假设实例名称就叫:datatable,一共两列:kcw_WheelIndety, kcw_lx_name。
填充数据或者获取数据后在datatable的最后插入两列:
datatable.Columns.Add("左", typeof(Int32));
datatable.Columns.Add("右", typeof(Int32));
datatable.Columns["左"].DefaultValue = 0; //设置默认值
datatable.Columns["右"].DefaultValue = 0;
在xaml页面中放上一个DataGrid,
<DataGrid x:Name="dg" IsReadOnly="True" CanUserAddRows="False"
AutoGenerateColumns="False"
AlternatingRowBackground="LightBlue">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding kcw_WheelIndety}" Width="120"
Header="轮标"/>
<DataGridTextColumn Binding="{Binding kcw_lx_name}" Width="120"
Header="轮型"/>
<DataGridTemplateColumn Header="左" Width="30">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RadioButton x:Name="rbLeft" Checked="rbLeft_Checked_1"
GroupName="LeftWheel"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="右" Width="30">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RadioButton x:Name="rbRight" Checked="rbRight_Checked_1"
GroupName="RightWheel"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
现在碰到一个问题,从上面的定义就可以看出来,表格的一行,就代表一个车轮。这个车轮要么是左,要么是右,不能同时既是左又是右,除了用常规Binding的方法之外,直接获取到选中行对应的模板列中的RadioButton,并直接对它进行操作怎么样?只需要在RadioButton的Checked事件中这样写:
private void rbLeft_Checked_1(object sender, RoutedEventArgs e)
{
RadioButton currentRb = sender as RadioButton;
ContentPresenter obj = dg.Columns[3].GetCellContent(dg.SelectedItem) as ContentPresenter;
DataTemplate dt = obj.ContentTemplate;
RadioButton rightbutton = dt.FindName("rbRight",obj) as RadioButton;
if (rightbutton.IsChecked == true)
rightbutton.IsChecked = false;
}
好啦,大功告成~