2011-09-13 13 views
1

更改取决于几个属性行的颜色我有对象,具有3属性:现在在Silverlight

CouldBeWhite bool 
CouldBeGreen bool 
CouldBeRed bool 

    If CouldBeWhite is true, then foreground of row should be white, if 
    CouldBeGreen is true, and CouldBeWhite is false, then row should be 
    Green If CouldBeRed is true, and and CouldBeWhite is false and 
    CouldBeGreen is false then row should be Red In other case row 
    should be blue. 

我的想法是让在视图模型的颜色,一些新的属性时,我会计算行的颜色。

或者也许有一些更好的方法来实现呢?

+1

这逻辑在我脑海里燃烧孔。怎么样enum ShouldBe {White,Green,Red}'并且完成。 – Will

回答

1

此枚举添加到您的项目: - :当每次CouldBeXXX性质改变

private RowState _RowState; 
public RowState RowState 
{ 
    get { return _RowState; } 
    set 
    { 
     if (value != _RowState) 
     { 
       _RowState = value; 
       NotifyPropertyChanged("RowState"); // Assumes typical implementation of INotifyPropertyChanged 
     } 
    } 
} 

private void UpdateRowState() 
{ 
    if (CouldBeWhite) 
     RowState = RowState.White; 
    else if (CouldBeGreen) 
     RowState = RowState.Green; 
    else if (CouldBeRed) 
     RowState = RowState.Red; 
    else 
     RowState = RowState.Blue; 
} 

呼叫UpdateRowState -

public enum RowState 
{ 
    Blue, 
    Red, 
    Green, 
    White 
} 

那么这个属性添加到您的视图模型。

考虑一下,你可能没有像前任那样将前景变成白色或红色或绿色。会有一些原因为什么它的白色,红色或绿色。因此,在你的代码中想一个简单的短名称来表示这些原因,并用那些更有意义的名称替换颜色名称。

现在去取StringToValueConverter的代码blog。这方面的一个实例添加到您的XAML中的UserControl.Resources

  <local:StringToObjectConverter x:Key="RowStateToBrush"> 
      <ResourceDictionary> 
       <SolidColorBrush Color="Red" x:Key="Red" /> 
       <SolidColorBrush Color="Green" x:Key="Green" /> 
       <SolidColorBrush Color="White" x:Key="White" /> 
       <SolidColorBrush Color="Blue" x:Key="__default__" /> 
      </ResourceDictionary> 
     </local:StringToObjectConverter> 

可以绑定一个TextBlock

<TextBlock Text="{Binding SomeTextProperty}" Foreground="{Binding RowState, Converter={StaticResource RowStateToBrush}}" /> 
1

在自定义值转换器中实现此逻辑可能会更干净。喜欢的东西:

public class RowColorConverter : IValueConverter 
     { 
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
      { 
       var myObj = value as MyObjectType(); 

       if (myObj.CouldBeWhite) 
       { 
        return new SolidColorBrush(Colors.White); 
       } 
       if (myObj.CouldBeGreen) 
       { 
        return new SolidColorBrush(Colors.Green); 
       } 
       if (myObj.CouldBeRed) 
       { 
        return new SolidColorBrush(Colors.Red); 
       } 
       return new SolidColorBrush(Colors.Blue); 

      } 

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
      { 
       return null; 
      } 
     }