gpt4 book ai didi

c# - 如何在 Silverlight 中为组单选按钮设置数据绑定(bind)?

转载 作者:太空狗 更新时间:2023-10-29 18:18:29 34 4
gpt4 key购买 nike

Sliverlight 提供了带有GroupName 的radio button 来将radio button 组合在一起,并且只能从多个选项中选择一个。就像:

<RadioButton GroupName="Option" Content="Option 1"></RadioButton>
<RadioButton GroupName="Option" Content="Option 2"></RadioButton>
<RadioButton GroupName="Option" Content="Option 3"></RadioButton>

然后在 VM 中,我只有一个属性用于此选项,比如说它是 MyChoice

public int MyChoice {get; set;}

那么如何在UI和VM之间为这种情况设置数据绑定(bind)?

最佳答案

使用转换器将 bool 值转换为整数:

在 Xaml 上,假设选项映射到 MyChoice 属性上的 1、2、3:

    <RadioButton GroupName="Option" Content="Option 1"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=1}"/>
<RadioButton GroupName="Option" Content="Option 2"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=2}"/>
<RadioButton GroupName="Option" Content="Option 3"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=3}"/>

在转换器中,注意我没有添加任何转换保护:

public class RadioButtonToIntConverter:IValueConverter 
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var myChoice = System.Convert.ToInt32(value);
return para == myChoice;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var isChecked = System.Convert.ToBoolean(value);
return isChecked ? para : Binding.DoNothing;
}
}

此外,您最好在 ViewModel 中实现 INotifyPropertyChanged。

关于c# - 如何在 Silverlight 中为组单选按钮设置数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17998562/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com