我试图将Enum
绑定到ComboBox
。我看到很多人使用ObjectDataProvider
,但我似乎无法访问它。我也注意到,有些人在Window.Resources
而不是Page.Resources
内使用它,但我无法找到它在Page.Resources
上的使用方式。我一直在寻找解决方案几个小时。如何使用ObjectDataProvider将枚举绑定到XAML中的ComboBox
我到目前为止有:
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],它清楚地显示了你所尝试的内容,以及一个错误描述。 –