WPF更改DataGridCheckBoxColumn的行为null false

时间:2014-12-09 13:24:16

标签: c# wpf datagrid

我有DataGrid和对象列表。 DataGrid仅用于可视化。现在我想改变绑定到DataGridCheckBoxColumn的行为。我想要三个这样的州:

null = unchecked
false = half checked
true = checked

现在它看起来像是:

null = half checked
false = unchecked
true = checked

我可以更改代码中的逻辑并将null视为false,将false视为null,但对我而言,更好的解决方案将只是不同的显示。 绑定看起来像那样

<DataGridCheckBoxColumn Header="SomeColumn" Binding="{Binding SomeProperty}" x:Name="SomeName" Visibility="Visible"/>

1 个答案:

答案 0 :(得分:0)

您可以像这样简单地使用转换器:

public class CheckBoxConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return false;
        if ((bool) value)
            return true;
        return null;   //value is false
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //Add the convert back if needed
        throw new NotImplementedException();
    }
}

,Xaml将是:

 <DataGridCheckBoxColumn Header="SomeColumn" Binding="{Binding SomeProperty,Converter={StaticResource CheckBoxConverter}}" x:Name="SomeName" Visibility="Visible"/>

并且不要忘记将Converter添加到您的窗口(或页面)资源:

 <Window.Resources>
    <converters:CheckBoxConverter x:Key="CheckBoxConverter"/>
</Window.Resources>