我将 textbox.text 值绑定(bind)到枚举类型。
我的枚举看起来像这样
public enum Type
{
Active,
Selected,
ActiveAndSelected
}
我不想完成的是在文本框上显示“事件模式”而不是“事件”等等。有可能这样做吗?如果我可以在 XAML 中完成它会很棒 - 因为我在样式文件 style.xaml 中拥有所有绑定(bind)
我试图使用描述属性,但似乎还不够
最佳答案
恕我直言,使用转换器是一种更好的方法。
您应该做的第一件事是实现一个简单的属性,以便将一些元数据添加到您的枚举元素。这是一个基本示例(为简单起见,没有国际化):
public enum StepStatus {
[StringValue("Not done yet")]
NotDone,
[StringValue("In progress")]
InProgress,
[StringValue("Failed")]
Failed,
[StringValue("Succeeded")]
Succeeded
}
接下来,您可以编写一个实用程序类,该类能够使用反射将枚举元素转换为其对应的 StringValue 表示。在 Google 中搜索“C# 中的字符串枚举 - CodeProject”,您会找到 CodeProject 的关于此的文章(对不起,我的低声誉不会让我添加链接..)
现在您可以实现一个转换器,它只是将转换委托(delegate)给实用程序类:
[ValueConversion(typeof(StepStatus), typeof(String))]
public class StepStatusToStringConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
String retVal = String.Empty;
if (value != null && value is StepStatus) {
retVal = StringEnum.GetStringValue((StepStatus)value);
}
return retVal;
}
/// <summary>
/// ConvertBack value from binding back to source object. This isn't supported.
/// </summary>
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture) {
throw new Exception("Can't convert back");
}
}
最后,您可以在 XAML 代码中使用转换器:
<resourceWizardConverters:StepStatusToStringConverter x:Key="stepStatusToStringConverter" />
...
<TextBox Text="{Binding Path=ResourceCreationRequest.ResourceCreationResults.ResourceCreation, Converter={StaticResource stepStatusToStringConverter}}" ... />
检查以下page ;它给出了一个支持国际化的例子,但基本上原理是一样的..
关于wpf - 将枚举类型绑定(bind)到文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3695976/