电量显示Binding Converter MVVM

用一个ProcessBar显示电量,低于20%时候,ForeGround为红色,否则为绿色,

页面使用了MVVM绑定到了ViewModel, ProcessBar XAML为

<ProgressBar  Maximum="100" Value="{Binding RemainPercent}" 
 Foreground="{Binding RemainPercent, Converter={StaticResource ForgroundConverter}}" ></ProgressBar>

其中  ForgroundConverter为资源的key

xmlns:converter ="clr-namespace:XXX.XXX"

<UserControl.Resources> <converter:PercentForgroundConverter x:Key="ForgroundConverter"/> </UserControl.Resources>
PercentForgroundConverter 为实现了IValueConverter的类,方法如下,
Brushes的命名空间为System.Windows.Media。
public class PercentForgroundConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double percent = (double)value;
            if (percent<=20)
            {
                return Brushes.Red;
            }
            return Brushes.Green;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

1.  当门限值(文中为20)固定情况下,可以这样写,若门限值不固定,可以将门限值以参数的形式传进来;

2. 只有当绑定的值(RemainPercent)发生变化以后,才会执行Convert 方法。

原文地址:https://www.cnblogs.com/pangkang/p/5874629.html