2017-05-11 58 views

回答

1

對於StatusType(枚舉?)和顏色之間的每個映射,我都會從每個枚舉實現一個ValueConverter到畫筆。

如果要重用顏色,請創建畫筆資源並將資源分配給轉換器。

public class PersonStatusToBrushConverter : DependencyObject, IValueConverter 
{ 
    public static readonly DependencyProperty WhenActiveProperty = 
     DependencyProperty.Register("WhenActive", typeof(Brush), typeof(PersonStatusToBrushConverter), 
      new PropertyMetadata(Brushes.Green)); 

    public static readonly DependencyProperty WhenInactiveProperty = 
     DependencyProperty.Register("WhenInactive", typeof(Brush), typeof(PersonStatusToBrushConverter), 
      new PropertyMetadata(Brushes.Orange)); 

    public static readonly DependencyProperty WhenDeceasedProperty = 
     DependencyProperty.Register("WhenDeceased", typeof(Brush), typeof(PersonStatusToBrushConverter), 
      new PropertyMetadata(Brushes.Red)); 

    public Brush WhenDeceased 
    { 
     get { return (Brush) this.GetValue(WhenDeceasedProperty); } 
     set { this.SetValue(WhenDeceasedProperty, value); } 
    } 

    public Brush WhenInactive 
    { 
     get { return (Brush) this.GetValue(WhenInactiveProperty); } 
     set { this.SetValue(WhenInactiveProperty, value); } 
    } 

    public Brush WhenActive 
    { 
     get { return (Brush) this.GetValue(WhenActiveProperty); } 
     set { this.SetValue(WhenActiveProperty, value); } 
    } 


    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     switch((PersonStatus)value) 
     { 
      case PersonStatus.Active: 
       return this.WhenActive; 
      case PersonStatus.Inactive: 
       return this.WhenInactive; 
      case PersonStatus.Deceased: 
       return this.WhenDeceased; 
      default: 
       return DependencyProperty.UnsetValue; 
     } 
    } 

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

對於文檔狀態,我會創建一個類似的轉換器。在一些不同的地方

<UserControl ... 
    xmlns:conv="clr-namespace:StatusConverters" > 
    <UserControl.Resources> 
     <SolidColorBrush x:Key="GreenBrush" Color="Green"/> 
     <SolidColorBrush x:Key="OrangeBrush" Color="Orange"/> 
     <SolidColorBrush x:Key="RedBrush" Color="Red"/> 
     <conv:PersonStatusToBrushConverter 
      x:Key="personStatusConverter" 
      WhenActive="{StaticResource GreenBrush}" 
      WhenInactive="{StaticResource OrangeBrush}" 
      WhenDeceased="{StaticResource RedBrush}"/> 
     <conv:DocumentStatusToBrushConverter 
      x:Key="documentStatusConverter" 
      WhenUnread="{StaticResource GreenBrush}" 
      WhenRead="{StaticResource OrangeBrush}" 
      WhenDeleted="{StaticResource RedBrush}"/> 
    </UserControl.Resources> 
    <Ellipse 
     Fill="{Binding Status, Converter={StaticResource personStatusToBrushConverter}" 
     Width="50" Height="50" /> 
+0

我們做的使用價值轉換器:

要與資源利用這一點。所以很高興看到這也可以用這種方式實現。謝謝你的提示!目前我想我會按照你的建議來實施它。 –

相關問題