【发布时间】: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