一、现象
使用Convert转换器,将string转换为bool,CheckBox无法点击选中
代码
<CheckBox Name="checkBoxMode"
IsChecked="{Binding CurrentVal,Converter={StaticResource StringToBool},Mode=TwoWay }”
HorizontalAlignment="Left"
Background="#00F76652"
Grid.Column="1"
VerticalAlignment="Center" >
</CheckBox>
[ValueConversion(typeof(string), typeof(bool))]
public class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string val = value as string;
if (val == "true")
return true;
else if (val == "false")
{
return false;
}
else
return null ;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value!=null)
{
return value.ToString();
}
else
{
return string.Empty;
}
}
}
二、解决方案
加UpdateSourceTrigger=Explicit
IsChecked="{Binding CurrentVal,Converter={StaticResource StringToBool},Mode=TwoWay,UpdateSourceTrigger=Explicit}"
UpdateSourceTrigger的默认值是Default,其他值有PropertyChanged、LostFocus和Explicit,绑定源不会更新除非你手动来操作
参考: