首页 > 解决方案 > 当且仅当满足某些先决条件时,是否可以启动转换器?

问题描述

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

<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”事件将被触发,值为真和假。现在,如果它是假的,我从转换器返回一个空字符串,它不会解析为 uint 并导致 UI 抱怨。

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

标签: c#wpfconverters

解决方案


使用这种方法,您似乎只想在任何IsChecked属性设置为时设置源属性true。然后您可以返回Binding.DoNothingwhen valis 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;
}

推荐阅读