根据WPF网格中的条件设置列文本值

时间:2017-02-21 06:24:07

标签: c# wpf

我有一个整数值(0,1,2),我需要将文本分别显示为'Error,Forward,Reverse'。

我可以使用GridViewDataColumn的setter属性在form.xaml中实现这一点。如果是这样,那么另一个值是什么? 对于数据列,我们必须将绑定定义为DataMemberBinding="{Binding Direction}",其中'Direction'是UInt16,此Direction属性是Observable集合的一部分。因此,我需要相应地将数据显示为字符串。

我只是在我的网格中定义了列

<telerik:GridViewDataColumn DataMemberBinding="{Binding Direction}" UniqueName= "Direction" Header="Direction" Width="85" TextAlignment="Left"  HeaderTextAlignment="Center" DisplayIndex="9" IsFilteringDeferred="True" >

如何添加触发器来实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以使用DataTrigger / IValueConvertor来实现

DataTrigger:

 <Style.Triggers>
      <!-- 1st trigger -->
      <DataTrigger Binding="{Binding Path=Direction}" Value="0">
        <Setter Property="Text" Value="Error"/>
      </DataTrigger>
      <!-- 2nd trigger -->
      <DataTrigger Binding="{Binding Path=Direction}" Value="1">
        <Setter Property="Text" Value="Forward"/>
      </DataTrigger>
      <!-- 3rd trigger -->

  <DataTrigger Binding="{Binding Path=Direction}" Value="2">
    <Setter Property="Text" Value="Reverse"/>
  </DataTrigger>

</Style.Triggers>

<强>转换器:

 <telerik:GridViewDataColumn DataMemberBinding="{Binding Direction,Convertor={StaticResource InttoDateConverter }" UniqueName= "Direction" Header="Direction" Width="85" TextAlignment="Left"  HeaderTextAlignment="Center" DisplayIndex="9" IsFilteringDeferred="True" >


public class InttoDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
                System.Globalization.CultureInfo culture)
        {
            switch (value.ToString().ToLower())
            {
                case "0":
                    return "Error!";
                case "1":
                    return "Forward";

                default:
                    return "Reverse";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, 
                System.Globalization.CultureInfo culture)
        {
           // only for two way binding
        }
    }

DataGrid列绑定:

<telerik:GridViewDataColumn Header="Direction" >
      <telerik:GridViewDataColumn.CellTemplate>
             <DataTemplate>
                      <TextBlock Text="{Binding Direction, Converter={StaticResource IntoToDataConvertor}, Mode=Default}"  />
             </DataTemplate>
      </telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>