添加 Bindinggroup NotifyOnValidationError 后 WPF 复选框绑定不起作用

WPF checkbox binding doesn't work after adding Bindinggroup NotifyOnValidationError

我有一个使用 MVVM 的对话框实现,它可以很好地与绑定等一起工作。因此选中一个复选框会在 ViewModel 中更新。

但是,我现在已经使用 WPF Binding.ValidationRules 实现了验证,并在对话框中向我的 stackpanel 添加了 BindingGroup

<StackPanel.BindingGroup>
  <BindingGroup NotifyOnValidationError="True">
  </BindingGroup>
</StackPanel.BindingGroup>

所以我可以捕获所有验证错误。但是添加 BindingGroup 也意味着我对 ViewModel 的绑定不再适用于复选框。 任何人都知道为什么复选框突然不起作用,但我的文本框仍然起作用?

您需要在 BindingGroup 上致电 CommitEdit:

if (stackPanel1.BindingGroup.CommitEdit())
{
    stackPanel1.BindingGroup.BeginEdit();
}

也许,在 UserControl 的某处有一个 Button 在单击事件处理程序中执行此操作,或者在 CheckBoxChecked 事件处理程序中执行此操作?

如果您正在寻找使用 MVVM 的验证,请继续使用 INotifyDataErrorInfo。

最佳做法是实现 INotifyDataErrorInfo 接口(如果您使用的是 .NET 4.5)或 IDataErrorInfo 接口。 Please refer to the blog post about data validation in WPF for more information and code samples: