在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没有直接支持它们。
我还没有尝试过依赖属性,因为我想先确保我不会错过一种更简单,更明显的解决方法。
创造它的最佳方法是什么?
您有两种方法可以解决此问题:
您可以通过附加属性扩展转换器,这些附加属性将由绑定填充
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"];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句