在 IValueConverter 中使用 FindResource

Erj*_*jon 2 c# wpf

我有这个值转换器,可以将数字转换为画笔颜色。我需要做的是将行更改return Brushes.Red;return (Brush)FindResource("PrimaryHueMidBrush");,这样我就可以返回主题的颜色。问题是我不知道如何声明(Brush)FindResource("PrimaryHueMidBrush");. 欢迎任何帮助。先感谢您。

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    double.TryParse(value.ToString(), out double val);

    if (val == 1)
    {
        return Brushes.Red;
    }
    else if(val == 0.5)
    {
        return Brushes.MediumVioletRed;
    }
    else if(val==0)
    {
        return Brushes.Transparent;
    }
    else
    {
        return Brushes.Transparent;
    }
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

Cle*_*ens 5

与其在转换器中调用 FindResource,不如为动态画笔添加一个或多个属性:

public class YourConverter : IValueConverter
{
    public Brush FirstBrush { get; set; }
    public Brush SecondBrush { get; set; }

    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        double val = (double)value;

        if (val >= 1)
        {
            return FirstBrush;
        }

        if (val >= 0.5)
        {
            return SecondBrush;
        }

        return Brushes.Transparent;
    }

    public object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在应用程序或窗口的资源中声明它,如下所示:

<local:YourConverter x:Key="YourConverter"
    FirstBrush="{StaticResource PrimaryHueMidBrush}"
    SecondBrush="MediumVioletRed"/>
Run Code Online (Sandbox Code Playgroud)