开发者

In wpf how to handle a event raised by a button inside user control in the page which uses that user control

开发者 https://www.devze.com 2023-01-01 09:40 出处:网络
I am using MVVM architecture. I had created a user control which contains a button control. I want the click event of the button control to be captured in page which uses this user control. How to do

I am using MVVM architecture. I had created a user control which contains a button control. I want the click event of the button control to be captured in page which uses this user control. How to do this? Plase he开发者_如何学编程lp :)


A button has a Command property. You should use that instead of the Click event by binding to an ICommand exposed by your ViewModel.

EDIT:

Two possibilities:

1) MVVM-way: Have a property for the command on your UserControl's ViewModel which you then set from your using page's ViewModel.

2) Non-MVVM way (although you could combine this with 1): Have a dependency property on your UserControl for the command, which you bind to in your UserControl's XAML. You can then bind to this dependency property from the using page.


You can define the event on a higher parent control:

Normally you would have:

<Grid>
      <Button Click="SomeMagicalEventHandler" />
</Grid>

But you can also define the event on the Grid as follows:

<Grid Button.Click="SomeMagicalEventHandler">
      <Button />
</Grid>

Of course, as long as its not handled in your event handler (arguments.Handled = true;) it will bubble upwards your visual tree until it reaches your page!

Hope this helps!

0

精彩评论

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