gpt4 book ai didi

c# - WPF RadioButton InverseBooleanConverter 不工作

转载 作者:行者123 更新时间:2023-11-30 16:19:06 36 4
gpt4 key购买 nike

我有两个 RadioButton,我将它们绑定(bind)到 ViewModel 中的 bool 属性。不幸的是,我在转换器中遇到错误,因为“targetType”参数为空。

现在我不希望通过的 targetType 参数为空(我希望 True 或 False)。但是我注意到 RadioButton 的 IsChecked 属性是一个可为 null 的 bool 值,所以这种解释。

我可以更正 XAML 中的某些内容还是应该更改解决方案的现有转换器?

这是我的 XAML:

<RadioButton Name="UseTemplateRadioButton" Content="Use Template" 
GroupName="Template"
IsChecked="{Binding UseTemplate, Mode=TwoWay}" />
<RadioButton Name="CreatNewRadioButton" Content="Create New"
GroupName="Template"
IsChecked="{Binding Path=UseTemplate, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}"/>

这是我正在使用解决方案范围内的现有转换器 InverseBooleanConverter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((targetType != typeof(bool)) && (targetType != typeof(object)))
{
throw new InvalidOperationException("The target must be a boolean");
}
return !(((value != null) && ((IConvertible)value).ToBoolean(provider)));
}

最佳答案

您需要更改转换器,或者使用新转换器可能更好。

[ValueConversion(typeof(bool?), typeof(bool))]
public class Converter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
{
throw new InvalidOperationException("The target must be a nullable boolean");
}
bool? b = (bool?)value;
return b.HasValue && b.Value;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}

#endregion
}

关于c# - WPF RadioButton InverseBooleanConverter 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15481916/

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