【问题标题】:How do I set the Foreground property of a TextBlock by TextBlock text value?如何通过 TextBlock 文本值设置 TextBlock 的 Foreground 属性?
【发布时间】:2011-05-05 05:32:57
【问题描述】:

可以通过 TextBlock 文本值设置 TextBlock 的前景属性吗? 例如:文本值为Mike,前景属性为Black,值为Tim,属性值为green等。我用google搜索,但没有找到任何解决方案。

【问题讨论】:

    标签: wpf binding converters foreground


    【解决方案1】:

    如果你想灵活地做一些智能的事情,比如动态地将文本映射到颜色等等,你可以使用一个 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 语句。

    【讨论】:

    • 要补充:如果不是使用静态资源,converter中的返回值应该是:new SolidColorBrush(Colors.Red)才能正确绑定字段值。
    【解决方案2】:

    您有一个模型视图(实现 INotifyPropertyChanged),它具有文本作为属性和前景色作为属性,让文本块将这两个属性绑定到模型视图。 color 属性可以依赖于 text 属性。

    【讨论】:

    • 我想你会发现使用这种方法比触发器/转换器方法更灵活和可测试。
    【解决方案3】:

    根据投票的 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 2021-01-23
      • 1970-01-01
      相关资源
      最近更新 更多