【问题标题】:Conditional StaticResource for color in Windows Phone 8Windows Phone 8 中颜色的条件静态资源
【发布时间】:2014-04-28 13:38:04
【问题描述】:

在 WP8 中,我想根据绑定中的布尔属性将 TextBlock 的前景色设置为不同的颜色。 此外,我还想使用 StaticResource 作为颜色。

我研究过的一种可能性是为此使用 ValueConverter,但到目前为止无法让它与 StaticResources 一起工作。 我尝试的代码类似于:

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BoolToColorConverter}}" />

还有我的转换器(我不认为返回字符串会起作用,但还是决定测试一下):

public class BoolToColorConverter : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        return (value is bool && (bool)value) ? "{StaticResource PhoneAccentBrush}" : "{StaticResource PhoneSubtleBrush}";
        }
}

此外,我研究过使用 DataTriggers,但我发现 WP8 没有直接支持它们。

我还没有尝试过依赖属性,因为我想首先确保我没有错过一种更简单、更明显的解决方法。

创建它的最佳方法是什么?

【问题讨论】:

  • 为什么不直接退回你想要的画笔呢?或者,如果您认为这太硬编码,请在转换器上添加 TrueBrush 和 FalseBrush 属性,在资源定义中将它们设置为您的特定画笔,然后 x:适当地命名它(例如 SubtleConverter)?
  • @Will,感谢您的评论。我想使用一个静态资源(例如PhoneAccentColor),所以现在不需要返回画笔本身。或者是否可以使用资源初始化画笔。我发现 TrueBrush、FalseBrush 的想法非常好。你有这方面的例子吗?
  • @Will,nvm,我修好了。谢谢你的想法。你能从中得出答案,以便我标记它吗?
  • 继续并标记 Viacheslav 正确。他有两种方法和代码。这是一个很常见的模式,所以不是我想出来的:)

标签: c# wpf silverlight windows-phone-8 staticresource


【解决方案1】:

你有两种方法可以解决这个问题:

您可以通过绑定填充的其他属性来扩展您的转换器

public class BooleanToBrushConverter
        : IValueConverter
    {
        public Brush TrueBrush { get; set; }
        public Brush FalseBrush { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                return (bool) value
                    ? TrueBrush
                    : FalseBrush;
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

现在可以通过页面资源来初始化了

<BooleanToBrushConverter x:Key="BooleanToBrushConverter" TrueBrush="{StaticResource PhoneAccentBrush}" FalseColor="{StaticResource PhoneSubtleBrush}" />

并像使用它一样简单

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BooleanToBrushConverter}}" />

第二个解决方案是修复代码以从应用程序资源中恢复画笔

public class BoolToColorConverter
  : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

        return (value is bool && (bool)value) ? Application.Current.Resources["PhoneAccentBrush"] : Application.Current.Resources["PhoneSubtleBrush"];
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多