#358 – 将RadioButton和枚举绑定(Binding a RadioButton to an Enumerated Type)

2016-10-14 11:25:38来源:CSDN作者:Libby1984人点击

你可以通过转换器将RadioButton 控件和一个枚举类型绑定。

XAML代码:

<Window.Resources>    <loc:EnumToBooleanConverter x:Key="enumToBooleanConverter" /></Window.Resources> <StackPanel HorizontalAlignment="Center" Margin="15">    <Label Content="Favorite animated character?"/>    <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.Gumby}}"                 Content="Gumby"/>    <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.PinkPanther}}"                 Content="Pink Panther"/>    <RadioButton IsChecked="{Binding Path=FavCharacter, Converter={StaticResource enumToBooleanConverter}, ConverterParameter={x:Static loc:CartoonCharacters.Magoo}}"                 Content="Mr. Magoo"/></StackPanel>


对应的枚举:

public enum CartoonCharacters{    Gumby,    PinkPanther,    Magoo}


用于绑定的该枚举类型的属性

public CartoonCharacters FavCharacter { get; set; }

转换器:
public class EnumToBooleanConverter : IValueConverter{    // Convert enum [value] to boolean, true if matches [param]    public object Convert(object value, Type targetType, object param, CultureInfo culture)    {        return value.Equals(param);    }     // Convert boolean to enum, returning [param] if true    public object ConvertBack(object value, Type targetType, object param, CultureInfo culture)    {        return (bool)value ? param : Binding.DoNothing;    }}

原文地址:https://wpf.2000things.com/2011/08/05/358-binding-a-radiobutton-to-an-enumerated-type/******************************************************译者注**************************************************上面的例子中,有三个RadioButton 控件,每个RadioButton 控件都和CartoonCharacters 枚举的一个值对应,当FavCharacter 属性的值和某个RadioButton控件对应的值一样的时候,该RadioButton 控件将被选中。

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台