WPF RadioButton InverseBooleanConverter not working

血红的双手。 提交于 2019-12-23 19:58:25

问题


I have two RadioButtons which I am binding to a boolean property in the ViewModel. Unfortunately I am getting an error in the converter because the 'targetType' parameter is null.

Now I wasn't expecting the targetType parameter coming through to be null (I was expecting True or False). However I noticed that the IsChecked property of the RadioButton is a nullable bool so this kind of explains it.

Can I correct something in the XAML or should I be changing the solution's existing converter?

Here's my 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}}"/>

This is the existing converter I am using solution wide 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)));
} 

回答1:


You need to change the converter, or what's probably even better, use a new converter.

[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
}


来源:https://stackoverflow.com/questions/15481916/wpf-radiobutton-inversebooleanconverter-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!