将标签前景颜色绑定到View Model WPF中的属性 [英] Binding the Label Foreground Color to a property in View Model WPF

查看:75
本文介绍了将标签前景颜色绑定到View Model WPF中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Xaml文件中的标签Forground Color绑定到View Model中的Color属性?


在此先感谢

How shall i bind the label Forground Color in my Xaml file to a Color property in View Model??


Thanks in advance

推荐答案

通常的方法是使用值转换器.这是一个示例,其中我用红色突出显示负数(在资产负债表类型的应用程序中为典型值):
The normal way to do this is to use a value converter. Here''s an example where I highlight negative numbers in red (typical in balance sheet type applications):
namespace MyNamespace
{
  using System;
  using System.Globalization;
  using System.Windows.Data;
  using System.Windows.Media;

  /// <summary>
  /// Converter to determine whether or not a number is negative, and apply
  /// conditional formatting if it is.
  /// </summary>
  public class NegativeNumberColorConverter : IValueConverter
  {
    #region IValueConverter Members
    /// <summary>
    /// Convert from the value to the colour brush.
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="targetType">The parameter is not used.</param>
    /// <param name="parameter">The parameter is not used.</param>
    /// <param name="culture">The parameter is not used.</param>
    /// <returns>The populated colour brush.</returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      var brush = new SolidColorBrush(Colors.Black);

      if (value == null)
      {
        return brush;
      }

      decimal result;
      var test = decimal.TryParse(value.ToString(), out result);

      if (!test || result >= 0)
      {
        return brush;
      }

      return new SolidColorBrush(Colors.Red);
    }

    /// <summary>
    /// Unused in this implementation.
    /// </summary>
    /// <param name="value">The parameter is not used.</param>
    /// <param name="targetType">The parameter is not used.</param>
    /// <param name="parameter">The parameter is not used.</param>
    /// <param name="culture">The parameter is not used.</param>
    /// <returns>The parameter is not used.</returns>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }

    #endregion
  }
}


前景不是颜色类型,而是画笔类型.

如果您在视图模型中创建brush类型的属性并进行绑定,则它可以工作.但是,使用值转换器根据视图模型中的属性值为您提供适当画笔的更好方法.
Foreground is not of type Color, its of type Brush.

If you create a property of type brush in your viewmodel and bind it works. However better approach to use a value converter to give you the appropriate brush based on property value in your viewmodel.


这篇关于将标签前景颜色绑定到View Model WPF中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆