CheckBox的绑定问题

一、现象

使用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,其他值有PropertyChangedLostFocusExplicit,绑定源不会更新除非你手动来操作

参考:

https://blog.csdn.net/sudazf/article/details/77745522
                  

猜你喜欢

转载自blog.csdn.net/sinat_31608641/article/details/107064895