将枚举类型绑定到文本框 [英] Binding enum type to textbox
问题描述
我将textbox.text值绑定到枚举类型。
我的枚举看起来像这样
I bind textbox.text value to enum type. My enum looks like that
public enum Type
{
Active,
Selected,
ActiveAndSelected
}
我不想做的是在文本框上显示活动模式而不是活动等等。有可能吗?如果我可以在XAML中修改它,那将是很棒的 - 因为我在样式文件style.xaml中的所有绑定
What I wan't to acomplish is to show on textbox "Active Mode" instead of "Active" and so on. Is it possible to do that? It would be great if I could acomplish that in XAML - because all bindings I have in style file style.xaml
我正在尝试使用Description属性,但它似乎是不够
I was trying to use Description attributes but it seems that it's not enough
推荐答案
IMHO使用转换器是一种更好的方法。
IMHO, using a converter is a better approach.
您应该做的第一件事是实现一个简单的属性,以便将一些元数据添加到您的枚举元素中。这是一个基本的例子(没有国际化简单):
The first thing you should do is implement a simple attribute in order to add some metadata to your enum elements. Here's a basic example (without internationalization for simplicity):
public enum StepStatus {
[StringValue("Not done yet")]
NotDone,
[StringValue("In progress")]
InProgress,
[StringValue("Failed")]
Failed,
[StringValue("Succeeded")]
Succeeded
}
旁边您可以编写一个实用程序类,可以使用反射将枚举元素转换为相应的StringValue表示形式。在Google中搜索C# - CodeProject中的字符串枚举,您会发现CodeProject关于这个的文章(抱歉,我的低声誉不会让我添加链接..)
Next to that, you can write a utility class able to convert from an enum element to its corresponding StringValue representation using reflection. Search in Google for "String Enumerations in C# - CodeProject" and you'll find CodeProject's article about this (sorry, my low reputation won't let me add the link..)
现在,您可以实现一个转换器,只需将转换委托给实用程序类:
Now you can implement a converter that simply delegates the conversion to the utility class:
[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代码中使用转换器:
Finally, you can use the converter in your XAML code:
<resourceWizardConverters:StepStatusToStringConverter x:Key="stepStatusToStringConverter" />
...
<TextBox Text="{Binding Path=ResourceCreationRequest.ResourceCreationResults.ResourceCreation, Converter={StaticResource stepStatusToStringConverter}}" ... />
检查以下页面;它给了一个支持国际化的例子,但基本上原则是一样的。
Check the following page; it gives an example that supports internationalization, but basically the principle is the same..
这篇关于将枚举类型绑定到文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!