MVVM Change the foreground label based on the value of the contents of the labels

The contents of my shortcuts are tied to a virtual machine and, based on the calculations, will be either negative or positive. If they are positive, I want the foreground to be a certain color and a different color if they are negative. Should I just handle all this in a virtual machine by snapping the front label frames? Only 4 shortcuts.

thanks

+4
source share
2 answers

I would let View handle how it displays the label. In my opinion, I would leave this color logic from ViewModel - since it should only process business rules, and not worry about how elements are displayed.

XAML:

<sdk:Label Content="{Binding NumericValue}" Foreground="{Binding NumericValue, Converter={StaticResource numToColor}}" /> 

View Model:

 private decimal _numValue = -1; public decimal NumericValue { get { return _numValue; } set { _numValue = value; RaisePropertyChanged("NumericValue"); } } 

Converter

 public class NumberToColorConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null || !(value is decimal)) return new SolidColorBrush(Colors.Black); var dValue = System.Convert.ToDecimal(value); if (dValue < 0) return new SolidColorBrush(Colors.Red); else return new SolidColorBrush(Colors.Green); } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } #endregion } 
+5
source

I'm going to assume that this is Silverlight or WPF

You need to create a ValueConverter. To do this, you need to create a new class that implements the IValueConverter interface. MSDN has a detailed explanation of how to do this.

Silverlight
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=VS.95%29.aspx

WPF
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=VS.100%29.aspx

+2
source

All Articles