2011-09-13 19 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. 

私の考えは、今私は、行の色を数えるだろうというとき、のviewmodel色でいくつかの新しい性質を持つことです。

これを実装するにはいくつかの良い方法がありますか?

+1

ロジックは私の心を通して穴を燃やすこと。どうすれば 'enumはShouldBe(White、Green、Red)'になるのでしょうか? – Will

答えて

1

プロジェクトにこの列挙を追加します -

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

次に、あなたのViewModelにこのプロパティを追加します - すべての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。

フォアグラウンドを白や赤、または緑に変えないようにしてください。いくつかの理由があるでしょうなぜその白、赤または緑です。したがって、あなたのコードでは、単純な短い名前を考えてその理由を表現し、色の名前をその意味のある名前に置き換えてください。

blogStringToValueConverterのコードを取得します。 UserControl.ResourcesであなたのXAMLに、このインスタンスを追加します。

  <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; 
      } 
     } 
関連する問題