如何在VM中绑定一个可空bool到RadRadioButton
本文关键字:一个 bool RadRadioButton VM 绑定 | 更新日期: 2023-09-27 18:11:48
我正在努力解决这个问题?在我的VM中,我有一个nullable bool
属性,我想绑定到是/否(true/false) RadRadioButton
。有人能给我指个正确的方向吗?
public bool? IsSDS { get; set; }
视图<telerik:Label Content="Self Directed Support" />
<StackPanel Orientation="Horizontal">
<telerik:RadRadioButton x:Name="SelfDirectedSupportYes" Content="Yes" />
<telerik:RadRadioButton x:Name="SelfDirectedSupportNo" Content="No" />
</StackPanel>
编辑
我以为这是工作,但我错了。只有"是"具有约束力。以下是我的看法,CreateAuthView
:
<StackPanel Orientation="Horizontal" Margin="3" Grid.Column="1" Grid.Row="2">
<telerik:RadRadioButton x:Name="Authorization_SelfDirectedSupportYes" GroupName="SDS" Content="Yes" />
<telerik:RadRadioButton x:Name="Authorization_SelfDirectedSupportNo" GroupName="SDS" Content="No" />
</StackPanel>
,这里是相应的部分在我的ViewModel, CreateAuthViewModel
:
public Authorization Authorization
{
get
{
return this.authorization;
}
set
{
if (authorization != value)
{
this.authorization = value;
NotifyOfPropertyChange(() => Authorization);
}
}
}
最后是我的模型的属性,Authorization
:
public bool? SelfDirectedSupportYes
{
get
{
return this.selfDirectedIndicator;
}
set
{
this.selfDirectedIndicator = value;
this.OnPropertyChanged();
}
}
IsChecked
也是Nullable<bool>
类型,因此您可以直接将其绑定为"yes"单选按钮。如果为两个单选按钮设置相同的GroupName
,则根本不需要绑定"否"单选按钮(因为选中"否"将取消选中"是")
<telerik:Label Content="Self Directed Support" />
<StackPanel Orientation="Horizontal">
<telerik:RadRadioButton x:Name="SelfDirectedSupportYes" GroupName="SelfDirectedSupportOption" Content="Yes" IsChecked="{Binding IsSDS}" />
<telerik:RadRadioButton x:Name="SelfDirectedSupportNo" GroupName="SelfDirectedSupportOption" Content="No" />
</StackPanel>
<telerik:RadRadioButton x:Name="SelfDirectedSupportYes" IsChecked="{Binding IsSDS}" Content="Yes" />
<telerik:RadRadioButton x:Name="SelfDirectedSupportNo" IsChecked="{Binding IsSDS, Converter={StaticResource InverseBooleanConverter}}" Content="No" />
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}