开发者

How to run a code before fired change check in a checkBox in WPF?

开发者 https://www.devze.com 2023-03-31 03:12 出处:网络
I mean, I开发者_如何学运维\'ve got a checkbox, and when it click on it.. I need to run a function to verify if can change IsChecked value or not.

I mean, I开发者_如何学运维've got a checkbox, and when it click on it.. I need to run a function to verify if can change IsChecked value or not.

It seems like a validation.


You can use the Checked (UnChecked/CheckedChanged) event(s) of the checkbox (depending on if its a WPF or a WinForms application):

CheckBox cb;
...
//WPF:
cb.Checked += (sender,e) => { if (!..check if new state is valid..) cb.Checked = !cb.Checked) };
cb.UnChecked += ...
//WinForms:
cb.CheckedChanged += ...

If the new checked state is not valid, it (un)checks the checkbox again and puts it in a valid state.

Another (and better) approach would be to disable the checkbox if a certain condition is not met (like a state of another control). It is confusing for the user if he or she checks a box and it's state is not changing without any feedback.

See MSDN for WPF / MSDN for WinForms for further informations.


The more WPF approach would be:

  1. Define a binding on Checked property of checkbox
  2. Assign binding Converter
  3. In converter decide either the return value of binded boolean property have to be True or False

If you use WPF force you do not jump into "windows forms" like solutions, as much as it possible (depends on time you have, performance impact, complexity ...). Try to follow WPF rules.


The best approach (MVVM) would be to bind the Click event on the check box to a Command on the view model. This would allow you to intercept the check event and also disable the ability based on business logic. Please see my example post here on command binding.

http://tsells.wordpress.com/2010/06/23/command-binding-with-wpf-and-silverlight-net-4-0-with-m-v-vm/

0

精彩评论

暂无评论...
验证码 换一张
取 消