c# - WPF RadioButton InverseBooleanConverter 不工作

标签 c# wpf radio-button ivalueconverter

我有两个 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/

相关文章:

c# - 如何在 Linq 上获得左连接

c# - JSON.NET:反序列化包含从接口(interface)派生的对象列表的类

c# - 如何通过按下按钮传递参数

wpf - 使用 Style 稍微修改控件模板

python - 单选按钮在 python 中无法正常工作

c# - 有没有办法将 OwinRequest 转换为 HttpRequestBase?

wpf - 鼠标悬停时更改 ListViewItem 背景颜色

c# - Telerik RadDocument 表大小问题

javascript - AngularJS - 未选中单选按钮

android - 如何以编程方式将图像设置为 RadioButton 参数?