简体   繁体   中英

WPF RadioButton Click with RaiseEvent

We have a simple control that inherits from a RadioButton. I would like to programmically check it.

If it were a button we would click we would normally do.

Button MyButton = ...
MyButtonClickArgs = new RoutedEventArgs(Button.ClickEvent, MyButton);
MyButton.RaiseEvent(MyButtonClickArgs);

So I figured I could do the following with a RadioButton.

RadioButton MyButton = ...
MyButtonClickArgs = new RoutedEventArgs(RadioButton.CheckedEvent, MyButton);
MyButton.RaiseEvent(MyButtonClickArgs);

No such luck however. Anyone know what I'm doing wrong.

Update: Upon further exploration is does appear the OnChecked event handler is being called. However the IsChecked state is false (so it does not do what I expected it to). If IsChecked is false I would expect it to be true by the time the event handler is called. At least that is the behavior if I physically click the button.

In your example you are only firing an event. Firing off the event does not automatically set the value of the Radio Button to IsChecked: true. Your example for Button Click is fine, but in the case of a Radio Button, you do not need to fire the event explicitly. You can directly set the property IsChecked = true

radioButton.IsChecked = true;

This will check the radio button and trigger your event calling your Checked event handler.

When you physically check the button, under the hoods it would set the property IsChecked and not just trigger the event.

Adding the relevant sections of the Radio Button Source code from WPF

/// <summary>
/// This override method is called from OnClick().
/// RadioButton implements its own toggle behavior 
/// </summary>
protected internal override void OnToggle() 
{ 
    IsChecked = true;
} 

Radion Button Source Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM