开发者

How to reference event handlers that are not in code-behind, but are in another object?

开发者 https://www.devze.com 2023-03-21 05:25 出处:网络
I can set the DataContext to any object, then have the properties of that object binded to my controls.

I can set the DataContext to any object, then have the properties of that object binded to my controls.

I want to do the same thing with event handlers. I have a class of event handlers that I want the xaml to use. However, the xaml looks for event hand开发者_如何学Clers in the code behind.

    <Button Click="OnSearch"/>

I get warnings that tells me that OnSearch does not exist in the code behind class.

  1. I want OnSearch to be in another object. How can I do that?
  2. What if I want the xaml to look for the event handler in the data context object?

I'm new to WPF and I'm trying to learn. I tried Binding on the event handlers but that obviously did not work!


I think for this purpose yuo should use Commands and not Events.

You need define YourRoutedEvent that derives from RoutedCommand

And bind it to the command of your Button control. In your YourRoutedEvent you can implement whatever complex logic you want to behave in different way during different states of your application, which is what you want probabbly, that's why asking about dynamic event binding.

Here is a sample link that dimonstrates command binding technique:

Command binding

Regards.

0

精彩评论

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