在WPF的数据网格文本列中将布尔值绑定为“是”否“

时间:2018-02-17 08:37:29

标签: c# wpf xaml datagrid

我需要在数据网格单元格中显示0和1布尔值为YES和NO。

<DataGridTextColumn Header="Active" Binding="{Binding stuen.IsDelete}" CanUserResize="False" Width="* "  HeaderStringFormat="" >
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment"  Value="Center"/>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

2 个答案:

答案 0 :(得分:4)

足够简单 - 您可以使用附加属性(例如YesNo)扩展状态模型,如:

public string YesNo
{
   get {return !IsDelete ? "No" : "Yes"}
}

现在将您的控件与status.YesNo绑定,而不是status.IsDelete。

或者 - 您可以在绑定元素中使用BooleanToYesNoConverter。基本上转换器将返回Yes表示status.IsDelete = true而No表示状态.IsDelete = false。

喜欢:

public class BooleanToYesNoConverter : IValueConverter
        {
                public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
                {
                        if((bool)value) return "Yes";
                         return "No"
                }

                public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
                {
                        return null;
                        /* not sure if you need convert back */
                }
        }

将此转换器添加为Xaml中的静态资源:

<Window.Resources>
                <local:BooleanToYesNoConverter  x:Key="BooleanToYesNoConverter" />
        </Window.Resources>

然后将绑定属性更新为:

Binding="{Binding stuen.IsDelete Converter={StaticResource BooleanToYesNoConverter}}"

其他替代解决方案是使用如下触发器:

<TextBlock.Style>
                <Style TargetType="{x:Type TextBlock}">
                    <Setter Property="Text" Value="" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding status.IsDelete}" Value="Yes">
                            <Setter Property="Text" Value="No" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>

答案 1 :(得分:2)

您可以将DataGridTextColumn替换为DataGridTemplateColumn

<DataGridTemplateColumn Header="Active" CanUserResize="False" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Text" Value="NO" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding stuen.IsDelete}" Value="True">
                                <Setter Property="Text" Value="YES" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>