【发布时间】:2011-05-05 05:32:57
【问题描述】:
可以通过 TextBlock 文本值设置 TextBlock 的前景属性吗? 例如:文本值为Mike,前景属性为Black,值为Tim,属性值为green等。我用google搜索,但没有找到任何解决方案。
【问题讨论】:
标签: wpf binding converters foreground
可以通过 TextBlock 文本值设置 TextBlock 的前景属性吗? 例如:文本值为Mike,前景属性为Black,值为Tim,属性值为green等。我用google搜索,但没有找到任何解决方案。
【问题讨论】:
标签: wpf binding converters foreground
如果你想灵活地做一些智能的事情,比如动态地将文本映射到颜色等等,你可以使用一个 Converter 类。我假设文本设置为绑定到某些东西,您可以在前台绑定到相同的东西,但通过自定义转换器:
<TextBlock Text="{Binding Path=Foo}"
Foreground="{Binding Path=Foo, Converter={StaticResource myConverter}" />
您的转换器将被定义为:
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = (string)value;
switch (text)
{
case "Mike":
return Colors.Red;
case "John":
return Colors.Blue;
default:
return Colors.Black;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
显然,您可以使用更智能的逻辑来处理新值等,而不是简单的 switch 语句。
【讨论】:
new SolidColorBrush(Colors.Red)才能正确绑定字段值。
您有一个模型视图(实现 INotifyPropertyChanged),它具有文本作为属性和前景色作为属性,让文本块将这两个属性绑定到模型视图。 color 属性可以依赖于 text 属性。
【讨论】:
根据投票的 cmets 的数量,我正在修改来自 @danut-enachioiu 的答案,以使用 Brushes 而不是 Colors 来实施解决方案,以便返回的值与 WPF 元素属性的类型相匹配。
TextBlock.Foreground is 'System.Windows.Media.Brushes'
这是修改后的代码……
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = (string)value;
switch (text)
{
case "Mike":
return Brushes.Red;
case "John":
return Brushes.Blue;
default:
return Brushes.Black;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
【讨论】: