将枚举类型绑定到文本框
我将 textbox.text 值绑定到枚举类型。 我的枚举看起来像
public enum Type
{
Active,
Selected,
ActiveAndSelected
}
我不想完成的是在文本框“活动模式”而不是“活动”等上显示。可以这样做吗?如果我能在 XAML 中完成这一点,那就太好了 - 因为我在样式文件 style.xaml 中拥有的所有绑定
我试图使用描述属性,但似乎这还不够
I bind textbox.text value to enum type.
My enum looks like that
public enum Type
{
Active,
Selected,
ActiveAndSelected
}
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
I was trying to use Description attributes but it seems that it's not enough
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恕我直言,使用转换器是更好的方法。
您应该做的第一件事是实现一个简单的属性,以便向枚举元素添加一些元数据。下面是一个基本示例(为了简单起见,没有国际化):
接下来,您可以编写一个实用程序类,能够使用反射将枚举元素转换为其相应的 StringValue 表示形式。在 Google 中搜索“C# 中的字符串枚举 - CodeProject”,您将找到 CodeProject 的相关文章(抱歉,我的低声誉不允许我添加链接..)
现在您可以实现一个转换器,只需将转换委托给实用程序类:
最后,您可以在 XAML 代码中使用转换器:
检查以下页面< /a>;它给出了一个支持国际化的例子,但基本上原理是一样的。
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):
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:
Finally, you can use the converter in your XAML code:
Check the following page; it gives an example that supports internationalization, but basically the principle is the same..
对于这个简单的情况,您不需要转换器。请改用 Stringformat。前导“{}”是一个转义序列,用于告诉解析器您不打算将它们用于另一个嵌套标记。如果您在绑定文本(由“{0}”指示)之前添加文本,则可以将其删除。
You do not need a converter for this simple case. Use Stringformat in stead. The leading '{}' are an escape sequence to tell the parser that you do not mean to use them for another nested tag. If you add text before the bound text (indicated by '{0}'), you can remove them.
您可以使用转换器来执行此操作。通常绑定到枚举,但向绑定添加 Converter 属性。该转换器是一个实现 IValueConverter 的类,它将由 WPF 调用。在那里,您可以添加“Mode”之类的后缀(或做任何您喜欢的事情)。
You can use a Converter to do this. Bind to the enum normally but add a Converter property to the binding. The converter is a class implementing IValueConverter, which will be called by WPF. There, you can add a suffix like "Mode" (or do whatever you like).