【问题标题】:Bind the foreground color of a TextBlock to local variable将 TextBlock 的前景色绑定到局部变量
【发布时间】:2013-02-11 08:24:18
【问题描述】:

我想将文本块的前景色绑定到局部变量。 如果变量没有值(=null),则前景色应为黑色,如果变量不为空,则前景色应为黑色或其他。 是否可以通过绑定解决?

【问题讨论】:

    标签: .net wpf binding


    【解决方案1】:

    您可以先使用值转换器,然后像这样定义您的转换器

    [ValueConversion (typeof(object), typeof(SolidColorBrush))]
    public class ObjectToBrushConverter : IValueConverter
    {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return new SolidColorBrush(Colors.Black);
            return new SolidColorBrush(Colors.Red);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    然后在 XAML 文件中将转换器定义为资源

        <Window.Resources>
            <local:ObjectToBrushConverter x:Key="ObjectToBrushConverter"/>
        </Window.Resources>
    

    然后你绑定到你的属性并提供你的转换器

        <TextBox Name="textb" Text="Hello" Foreground="{Binding Path=MyObject,  Converter={StaticResource ResourceKey=ObjectToBrushConverter}}">
    

    查看值转换器上的 msdn http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

    当然假设您在本例中将变量定义为公共属性和 Object 类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2010-12-01
      • 1970-01-01
      • 2014-11-05
      • 2012-08-27
      • 2013-08-30
      • 1970-01-01
      相关资源
      最近更新 更多