当且仅当满足某些前提条件时,才可能触发转换器?

时间:2019-09-12 08:58:39

标签: c# wpf converters

我有一组单选按钮,它们都连接到视图模型中的同一变量

<RadioButton Content="20" Margin="5,0" GroupName="open_rb" 
IsChecked="{Binding Path=mOpen.Threshold, Mode=OneWayToSource, Converter={StaticResource RadioBoolToIntConverter}, ConverterParameter=20, UpdateSourceTrigger=PropertyChanged}" />

<RadioButton Content="50" Margin="5,0" GroupName="open_rb"
  IsChecked="{Binding Path=mOpen.Threshold, Mode=OneWayToSource, Converter={StaticResource RadioBoolToIntConverter}, ConverterParameter=50, UpdateSourceTrigger=PropertyChanged}"/>

<RadioButton Content="70" Margin="5,0" GroupName="open_rb"
 IsChecked="{Binding Path=mOpen.Threshold, Mode=OneWayToSource, Converter={StaticResource RadioBoolToIntConverter}, ConverterParameter=70, UpdateSourceTrigger=PropertyChanged}"/>

我的转换器是-

public class RadioBoolToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();

        //should not hit this part
        int integer = (int)value;
        if (integer == int.Parse(parameter.ToString()))
            return true;
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //bool to int (if bool is true then pass this val)
        bool val = (bool)value;
        if (val == true)
            return UInt32.Parse(parameter as string);

        else
        {
            //when you uncheck a radio button it fires through 
            //isChecked with a "false" value
            //I cannot delete this part, because then all code paths will not return a value
            return "";
        }
    }
}

基本上的想法是,如果单击某个单选按钮,则转换器会将20或30或70(取决于单击哪个单选按钮)传递给mOpen.Threshold,它是一个无符号的int。

现在,如果选中或不选中单选按钮,则true和false值将触发单选按钮“ isChecked”事件。现在,如果它为假,我将从转换器返回一个空字符串,该字符串不会解析为uint并导致UI抱怨。

如果选中单选按钮,是否可以仅使用此转换器?这意味着对于该组,如果单击单选按钮,则仅应触发此转换器一次,而不应触发两次。

1 个答案:

答案 0 :(得分:1)

使用这种方法,似乎您只想在IsChecked属性中的任何一个设置为true时才设置source属性。然后,当Binding.DoNothingval时,可以返回false

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    //bool to int (if bool is true then pass this val)
    bool val = (bool)value;
    if (val == true)
        return UInt32.Parse(parameter as string);

    return Binding.DoNothing;
}