如何从转换器返回资源样式?

时间:2018-01-27 19:10:09

标签: c# wpf

假设我需要根据Foreground的当前项的值设置不同的DataTemplate

<DataGridTemplateColumn Header="5">
     <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
               <Text="{Binding Match5}" TextAlignment="Center" HorizontalAlignment="Center">
                    <TextBlock.Style>
                         <Style TargetType="{x:Type TextBlock}">
                               <Setter Property="Background" Value="{Binding Match5, Converter={StaticResource NameToBrushConverter}}"/>
                               <Setter Property="Foreground" Value="{Binding Match5, Converter={StaticResource ForegroundConverter}}"/>
                               <Setter Property="Width" Value="{Binding Match5, Converter={StaticResource NameToWidthConverter}}" />
                        <Style.Triggers>
                  </TextBox.Style> 
             ...

我创建了一个转换器:

public class ForegroundConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var input = value as string;

        if (input.Contains("-"))
            return "MaterialDesignBody";

        return "White";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

现在当项目不包含-时,设置了白色前景,但当值包含-时,我需要返回DynamicResource提供的MaterialDesignInXaml,但是我在输出控制台中收到此错误:

  

System.Windows.Data错误:6:'DynamicValueConverter'转换器无法转换值'MaterialDesignBody'(类型'String');如果可用,将使用后备值。 BindingExpression:路径=匹配1; DataItem ='LatestFiveMatchRow'(HashCode = 87685); target元素是'TextBlock'(Name =''); target属性是'Foreground'(类型'Brush')FormatException:'System.FormatException:无效的令牌。

任何想法或提示?感谢。

1 个答案:

答案 0 :(得分:1)

请注意

return "White";

仅适用于内置自动类型转换。有一个BrushConverter类注册为TypeConverter,用于target属性或其类型,即Brush:

[TypeConverterAttribute(typeof(BrushConverter))]
[LocalizabilityAttribute(LocalizationCategory.None, Readability = Readability.Unreadable)]
public abstract class Brush : Animatable, IFormattable

这个TypeConverter(不能与Binding的IValueConverter混淆)能够转换着名的刷子名称,如&#34; White&#34;等同于Brushes类,即Brushes.White。但是,它无法转换&#34; MaterialDesignBody&#34;。您必须执行资源查找并自行返回相应的Brush资源:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value.ToString().Contains("-"))
    {
        return (Brush)Application.Current.FindResource("MaterialDesignBody");
    }

    return Brushes.White;
}