当且仅当满足某些先决条件时,是否有可能触发转换器?

Is it possible to fire a converter if and only if some pre-condition is satisfied?

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

<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,这是一个无符号整数。

现在,单选按钮 "isChecked" 事件会在单选按钮是否被选中时触发,其值为 true 和 false。现在,如果它是假的,我 return 一个来自转换器的空字符串,它不解析为 uint 并导致 UI 抱怨。

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

使用这种方法,您似乎只想在任何 IsChecked 属性设置为 true 时设置源 属性。当 valfalse:

时,您可以 return Binding.DoNothing
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;
}