我需要一个转换器来解析和绑定枚举吗
在我的数据库中,我有 2 列(种类和优先级),类型为 int。我还有一个带有 Kind 和 Priority 值的枚举。但是当我尝试将它们显示到 GridViewColumn 中时,它显示整数而不是枚举值。我需要转换器吗这是枚举:
public enum Kind
{
None = 0,
Task = 1,
Assignment = 2,
Quiz = 3,
Test = 4,
Exam = 5,
Project = 6,
}
public enum Priority
{
None = 0,
Low = 1,
Medium = 2,
High = 3,
Top = 4,
}
和我的 XAML:
<GridViewColumn x:Name="PriorityColumn" Header="Priority" Width="60" DisplayMemberBinding="{Binding Path=Priority}" />
<GridViewColumn x:Name="KindColumn" Header="Kind" Width="60" DisplayMemberBinding="{Binding Path=Kind}" />
In my database I have a 2 columns (Kind and Priority) that are of type int. I also have an enum with the values of Kind and Priority. But when I try to display them into a GridViewColumn, it shows the integers and not the enum values. Do I need a converter Here is the enums:
public enum Kind
{
None = 0,
Task = 1,
Assignment = 2,
Quiz = 3,
Test = 4,
Exam = 5,
Project = 6,
}
public enum Priority
{
None = 0,
Low = 1,
Medium = 2,
High = 3,
Top = 4,
}
And my XAML:
<GridViewColumn x:Name="PriorityColumn" Header="Priority" Width="60" DisplayMemberBinding="{Binding Path=Priority}" />
<GridViewColumn x:Name="KindColumn" Header="Kind" Width="60" DisplayMemberBinding="{Binding Path=Kind}" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 Priority 和 Kind 属性声明为 int 类型,那么是的,您将需要一个转换器。 WPF 无法知道声明为整数的属性是否需要解释为枚举中的值。
如果 Priority 和 Kind 属性分别声明为 Priority 和 Kind 类型,那么它应该可以正常工作:WPF 通过调用 ToString() 来显示枚举,这将产生枚举值的名称。
例如:(
填充 Job 对象时,您当然需要将从数据库中出来的 int 转换为 Kind 和 Priority,或者坚持使用 int 支持字段并在 getter 和 setter 中进行转换。如果您使用一个好的 ORM 那么它应该能够为你处理这个问题。)
If the Priority and Kind properties are declared as type int, then yes, you will need a converter. WPF has no way of knowing that the properties declared as integer need to be interpreted as values from the enums.
If the Priority and Kind properties are declared as type Priority and Kind respectively, then it should just work: WPF displays enums by calling ToString() on them which will result in the name of the enum value.
For example:
(When populating a Job object you will of course need to cast the ints coming out of the database to Kind and Priority, or you stick with an int backing field and do the casting in the getter and setter. If you are using a good ORM then it should be able to take care of this for you.)