0
如果一個應用程序有一組狀態的。 例如WPF中爲實現應用程序中不同狀態的交通燈顏色的最佳方式是什麼?
- 資格(活動[綠色],無效[橙],死者[紅色])
- 文檔狀態(未讀[橙],讀[綠色],刪除[紅色])
正如你可以告訴所有這些狀態組使用相同的顏色。 你們推薦這個在WPF中實現嗎?我正在進行重構,希望確保它是可重用的,可讀的和可理解的。
如果一個應用程序有一組狀態的。 例如WPF中爲實現應用程序中不同狀態的交通燈顏色的最佳方式是什麼?
正如你可以告訴所有這些狀態組使用相同的顏色。 你們推薦這個在WPF中實現嗎?我正在進行重構,希望確保它是可重用的,可讀的和可理解的。
對於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" />
我們做的使用價值轉換器:
要與資源利用這一點。所以很高興看到這也可以用這種方式實現。謝謝你的提示!目前我想我會按照你的建議來實施它。 –