c# - 当且仅当满足某些先决条件时,是否可以启动转换器?
问题描述
我有一组单选按钮都连接到视图模型中的同一个变量
<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 抱怨。
如果选中单选按钮,是否可以仅使用此转换器?这意味着对于这个组,如果我点击一个单选按钮,这个转换器应该只被触发一次,而不是两次。
解决方案
使用这种方法,您似乎只想在任何IsChecked
属性设置为时设置源属性true
。然后您可以返回Binding.DoNothing
when val
is 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;
}
推荐阅读
- c - 使用 cjson 解析 json
- ios - 无法连接到 Firebase 和 Auth
- html - 元素宽度在 chrome 和 Internet Explorer 中有所不同
- c - 使用 ncurses 从文件中打印 ascii 艺术行为奇怪
- tablesorter - 有没有办法将tablesorter表导出到excel?
- javascript - 如何检查按钮单击时显示的字段是否已加载
- ms-access - 如何在 From 和 To 字段中实现日期过滤
- ecmascript-6 - TypeError:无法读取未定义的属性“createProduct”?(来自 graphql mutation.js 文件)
- python - Django中的散景图返回一个空白页
- windows - 在批处理脚本中检索注册表字符串的值