C# Windows Phone 8.1 XAML:将枚举值放入XAML属性

C# Windows Phone 8.1 XAML:将枚举值放入XAML属性,c#,wpf,xaml,enums,windows-phone-8.1,C#,Wpf,Xaml,Enums,Windows Phone 8.1,这是我的枚举结构: namespace MyNS { enum MyEnum { MyValOne = 1, MyValTwo = 2 } } 与此相反: <RadioButton x:Name="1" /> <RadioButton x:Name="2" /> 我想要这样的东西:(x:Name属性不重要。任何属性都可以) 我该怎么做呢?您只需要这样一个枚举转换器 public class EnumRad

这是我的枚举结构:

namespace MyNS
{
    enum MyEnum
    {
        MyValOne = 1,
        MyValTwo = 2
    }
}
与此相反:

<RadioButton x:Name="1" />
<RadioButton x:Name="2" />

我想要这样的东西:(x:Name属性不重要。任何属性都可以)



我该怎么做呢?

您只需要这样一个枚举转换器

public class EnumRadioButtonConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value.ToString() == parameter.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return (bool)value ? Enum.Parse(typeof(MyEnum), parameter.ToString(), true) : null;
    }
}
这就是你使用它的方式(别忘了给他们一个
GroupName
)。当然,您需要在viewmodel中定义一个
SelectedEnum
属性(类型为
MyEnum

<RadioButton IsChecked="{Binding SelectedEnum, ConverterParameter=MyValTwo, Converter={StaticResource EnumRadioButtonConverter}, Mode=TwoWay}" GroupName="MyRadioButtonGroup" />
<RadioButton IsChecked="{Binding SelectedEnum, ConverterParameter=MyValOne, Converter={StaticResource EnumRadioButtonConverter}, Mode=TwoWay}" GroupName="MyRadioButtonGroup" />

要使用转换器,您需要在参考资料部分中引用它

<Page.Resources>
    <local:EnumRadioButtonConverter x:Key="EnumRadioButtonConverter" />


请找到一个工作样本。

您的最终目标是什么?你想绑定枚举吗?您不能绑定属性,例如
x:Name
。那么标签属性呢?我有枚举值的单选按钮。然后我在代码中使用它们。那么你需要从选定的radiobutton获取枚举吗?@RenDishen,是的,你是对的。那么我如何获取选定的radiobutton值呢?而我获取资源EnumRadioButton转换器找不到。如何将类引用到我的XAML?请参阅更新的答案。您需要定义一个
SelectedEnum
属性,并将
IsChecked
绑定到该属性。要使用转换器,首先需要在xaml中引用它。当然,请查看我的更新答案。随附工作样本。:)谢谢你,贾斯汀。这真的很有帮助。但我认为这可能更简单。无论如何谢谢你。
<Page.Resources>
    <local:EnumRadioButtonConverter x:Key="EnumRadioButtonConverter" />