Enum
をComboBox
にバインドしようとしています。私はObjectDataProvider
を使用している多くの人々を見ましたが、私はそれにアクセスできないようです。私はまた、Page.Resources
ではなくWindow.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]と、間違ったことの_precise_の説明を提供してください。 –