【问题标题】:Is it possible to fire a converter if and only if some pre-condition is satisfied?当且仅当满足某些先决条件时,是否可以启动转换器?
【发布时间】:2020-01-14 02:58:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# wpf converters


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2016-07-04
      • 1970-01-01
      相关资源
      最近更新 更多