我正在尝试将一个枚举类型绑定到ComboBox上。我看到很多人使用ObjectDataProvider,但我似乎无法访问它。我也注意到有些人将其放在Window.Resources中而不是Page.Resources中,但我找不到如何在Page.Resources中使用它。我已经寻找解决方案几个小时了。
我目前所拥有的:
XAML
我目前所拥有的:
XAML
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sports;assembly=Sports"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModel="using:Sports.ViewModel"
xmlns:model="using:Sports.Model"
xmlns:system="using:System"
x:Class="Sports.MainPage"
mc:Ignorable="d">
<Page.DataContext>
<ViewModel:CreateSubsVM/>
</Page.DataContext>
<Page.Resources>
<ObjectDataProvider></ObjectDataProvider>
</Page.Resources>
</Grid>
</Page>
C#
public enum SubsAmount
{
[Display(Description = "One Year")]
Oneyear = 0,
[Display(Description = "Two Years")]
TwoYears = 1,
[Display(Description = "Three Years")]
ThreeYears = 2
}
public class ComboboxConverter: IValueConverter
{
public string GetEnumValues(Enum enumObj)
{
DisplayAttribute attribute = enumObj.GetType().
GetRuntimeField(enumObj.ToString()).
GetCustomAttributes(typeof(SubsAmount), false).
SingleOrDefault() as DisplayAttribute;
return attribute == null ? enumObj.ToString() : attribute.Description;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
return GetEnumValues((Enum) value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return Enum.ToObject(targetType, value);
}
}
ObjectDataProvider
,因为你使用一个空元素进行了声明。只有提供必要的值才能使其正常工作。如果正确操作,它将会正常运作。请提供一个良好的[mcve],清楚地展示你尝试过的所有内容,并提供一个精确的描述出现了什么问题。 - Peter Duniho