一、问题场景
某些场景下,需要通过 VM 中的与 CheckBox 中 IsChecked 进行数据Binding,代码内容如下:
Xaml代码
<TabItem Header="测试"> <TabItem.Resources> <local:ViewModel x:Key="ViewModel"></local:ViewModel> </TabItem.Resources> <CheckBox Content="测试" DataContext="{StaticResource ViewModel}" Command="{Binding CheckCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self},Path=IsChecked}"></CheckBox> </TabItem>
ViewModel代码
public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string name = "") { if (string.IsNullOrEmpty(name)) { return; } PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } private bool isChecked; public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged(); } } private ICommand checkCmd; /// <summary> /// 选中指令 /// </summary> public ICommand CheckCmd => checkCmd ??= new DelegateCommand<bool>(CheckStatus); private void CheckStatus(bool ischecked) { } }
运行效果异常结果:
二、解决方案
由于CheckBox的 Command 绑定了 CheckCmd 命令,参数传递当前 IsChecked 控件属性,需要注意的是,IsChecked 类型为 bool? 类型,源码如下:
public class ToggleButton : ButtonBase { [Category("Appearance")] [TypeConverter(typeof(NullableBoolConverter))] [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public bool? IsChecked { get { } set { } } }
运行时,触发执行 Command,转换过程中,无法将 CommandParameter 对应的参数由 null 转换为 bool 类型,故而报错。
解决方案是,将 ViewModel 中命令 CheckCmd中对应的执行函数类型 bool 转换为 bool?,ViewModel变更如下:
private ICommand checkCmd; /// <summary> /// 选中指令 /// </summary> public ICommand CheckCmd => checkCmd ??= new DelegateCommand<bool?>(CheckStatus); private void CheckStatus(bool? ischecked) { }
再次运行,则不再报错。
