一、枚举转换器
枚举类
public enum 进程状态
{
全部,
新增,
开发中,
已完成
}
枚举转换器
public class 枚举转换器 : MarkupExtension
{
private Type _enumType;
public Type EnumType
{
get { return _enumType; }
set
{
if (value != _enumType)
{
if (null != value)
{
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (!enumType.IsEnum)
{
throw new ArgumentException("Type must bu for an Enum");
}
}
_enumType = value;
}
}
}
public 枚举转换器()
{
}
public 枚举转换器(Type enumType)
{
EnumType = enumType;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (null == _enumType)
{
throw new InvalidOperationException("The EnumTYpe must be specified.");
}
var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
var enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == _enumType)
{
return enumValues;
}
var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}
xmal页面(窗体)进行绑定
<ComboBox
Height="24"
Width="100"
x:Name="cb进程状态"
Foreground="White"
SelectedIndex="0"
Style="{StaticResource Combobox样式}"
ItemsSource="{Binding Source={local:枚举转换器 {x:Type local:进程状态}}}"
SelectionChanged="进程状态下拉框_选择变更事件"/>
二、界面显示:数字转文字、颜色转换器
Convert转换类
#region 进程状态转换器
public class 进程状态转换器 : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
int 进程状态 = (int)value;
string 完成状态 = string.Empty;
switch (进程状态)
{
case 0:
完成状态 = "新增";
break;
case 1:
完成状态 = "进行中";
break;
case 99:
完成状态 = "已完成";
break;
default:
break;
}
return 完成状态;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
#endregion
#region 进程状态颜色转换器
public class 进程状态颜色转换器 : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.White;
int 进程状态 = (int)value;
SolidColorBrush 颜色 = Brushes.White;
switch (进程状态)
{
case 0:
颜色 = Brushes.Red;
break;
case 1:
颜色 = Brushes.Blue;
break;
case 99:
颜色 = Brushes.Green;
break;
default:
break;
}
return 颜色;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
#endregion
xmal页面(窗体)进行绑定
<Page.Resources>
<local:进程状态转换器 x:Key="进程状态转换器"/>
<local:进程状态颜色转换器 x:Key="进程状态颜色转换器"/>
</Page.Resources>
<TextBlock
Text="{Binding 进程状态,Converter={StaticResource 进程状态转换器}}"
Foreground="{Binding 进程状态,Converter={StaticResource 进程状态颜色转换器}}"/>