我正在向数据网格动态添加 itemsource:
datagrid.ItemsSource = _table.DefaultView;
foreach (DataColumn column in _table.Columns)
{
if (column.DataType == typeof(bool))
{
var dgrcl = new DataGridCheckBoxColumn
{
IsThreeState = false,
Header = column.Caption,
Binding = new Binding(column.ColumnName),
Width = new DataGridLength(15, DataGridLengthUnitType.Star)
};
datagrid.Columns.Add(dgrcl);
}
else
{
var dgrcl = new DataGridTextColumn();
dgrcl.Binding = new Binding(column.ColumnName);
dgrcl.Header = column.Caption;
datagrid.Columns.Add(dgrcl);
}
}
但是,如果我向 Datagrid 添加一个新行(带有复选框列) - 复选框是三态的。我尝试在 xaml 中添加下一个代码:
<Style TargetType="CheckBox" x:Key="dgrChkBoxStyle">
<Setter Property="IsThreeState" Value="False"></Setter>
<Setter Property="IsChecked" Value="True"></Setter>
</Style>
<DataGrid Name="datagrid" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Margin="10" VerticalAlignment="Stretch" AlternatingRowBackground="Honeydew" AlternationCount="2" AutoGenerateColumns="False">
<DataGridCheckBoxColumn>
<DataGridCheckBoxColumn.ElementStyle>
<Style TargetType="CheckBox" BasedOn="{StaticResource dgrChkBoxStyle}"></Style>
</DataGridCheckBoxColumn.ElementStyle>
</DataGridCheckBoxColumn>
</DataGrid>
但是有一个例外是“在使用 ItemsSource 之前,Items 集合必须为空”。
我是 WPF 的新手,请多多指教,如何制作只有两种状态的复选框?