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# - ASP.NET Core 中 AppSettings.json 内的 POCO 对象数组

wpf - 数据显示之前,忙碌指示灯不显示

Python tkinter Entry 小部件状态通过单选按钮切换

android - 单选按钮文本 "Recycled"?

c# - C#中如何获取对象的值

c# - DbMigrator.Update 导致数据库 'name' 已存在

c# - 城堡动态代理 : How to Proxy Equals when proxying an interface?

WPF 更改鼠标悬停和按下的按钮样式

wpf - Visiblox,WPF : Display labeled markers in a chart

javascript - jquery 显示和隐藏图像不起作用