在转换器中使用资源

Gus*_*rra 2 c# xaml windows-phone windows-phone-8

我需要将刷子设置为红色或橙色,具体取决于某些条件,如果没有满足任何条件,则需要回退到默认刷子.

如果Windows手机有样式触发器,这将是微不足道的,但事实并非如此,我必须为每个场景创建一个特殊用途的转换器,如下所示:

public class StatusToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var status = (Status)value;
        if (status.IsCancelled)
        {
            return new SolidColorBrush(Colors.Red);
        }
        else if (status.IsDelayed)
        {
            return new SolidColorBrush(Colors.Orange);
        }
        else 
        {
            return parameter;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<TextBlock Foreground="{Binding Status, 
                                Converter={StaticResource statusToColorConverter},
                                ConverterParameter={StaticResource PhoneForegroundBrush}}" />
Run Code Online (Sandbox Code Playgroud)

但现在我需要一个返回PhoneForegroundBrushPhoneDisabledBrush根据条件返回的转换器.

我无法传递两个参数,Windows Phone也不支持MultiBindings.我虽然这样:

<TextBlock Foreground="{Binding Status, 
                                Converter={StaticResource statusToColorConverter},
                                ConverterParameter={Binding RelativeSource={RelativeSource Self}}
Run Code Online (Sandbox Code Playgroud)

所以我可以在参数中获取文本块,然后使用它来查找资源,但它也不起作用.

有任何想法吗?

Kev*_*sse 6

您可以直接将转换器声明为转换器上的属性:

public class StatusToColorConverter : IValueConverter
{
    public Brush CancelledBrush { get; set; }
    public Brush DelayedBrush { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var status = (Status)value;

        if (status.IsCancelled)
        {
            return this.CancelledBrush;
        }

        if (status.IsDelayed)
        {
            return this.DelayedBrush;
        }

        return parameter;
    }

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

然后,在初始化转换器时从XAML填充它们:

<my:StatusToColorConverter x:Key="StatusToColorConverter" CancelledBrush="{StaticResource CancelledBrush}" DelayedBrush="{StaticResource DelayedBrush}" />
Run Code Online (Sandbox Code Playgroud)