0

我正在显示包含“状态”列的表中的数据,现在当我将单元格文本属性绑定到该表的返回集合时,此列包含两个值 0 和 1 0 => Daily 1 => Monthly 通过使用 mvvm 结构,它显示 0 和 1。应该显示我想要的,而不是 0,Daily 和 1 for Monthly。有没有办法做到这一点?

4

1 回答 1

1

是的,您可以通过实现接口IValueConverter来创建绑定转换器。

public class IntTextConverter : IValueConverter
{
    // This converts the int object to the string
    // to display 0 => Daily other values => Monthly.
    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        // You can test type an value (0 or 1) and throw exception if
        // not in range or type
        var intValue = (int)value;
        // 0 => Daily 1 => Monthly
        return intValue == 0 ? "Daily" : "Monthly";
    }

    // No need to implement converting back on a one-way binding
    // but if you want two way
    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        return value == "Daily" ? 0 : 1;
    }
}

在 Xaml 中,文本块上的示例绑定:

<Grid.Resources>
   <local:IntTextConverter x:Key="IntTextConverter" />
</Grid.Resources>
...
<TextBlock Text="{Binding Path=Status, Mode=OneWay,
           Converter={StaticResource IntTextConverter}}" />
于 2013-05-17T07:09:30.917 回答