Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello all,

I am new to WPF. I have built a complex UserControl in Blend 4 and it works fine.

I want to bind the click of any buttons in my usercontrol to my main resource in c#.

How can i tell my usercontrol, that the click is not in my code of the usercontrol. The click event must bind to my window inside code...

Thanks for all answers.

Reinhard
Posted
Updated 29-Jul-10 3:10am
v2

Expose one event handler in the usercontrol and use it from the window where you placed your usercontrol. Better you search for delegates.
 
Share this answer
 
Comments
Keith Barrow 29-Jul-10 9:30am    
I suggest you take a look at my answer, you can bind the command to any object with suitable methods to handle it being raised. This is the preferred method of doing it as it doesn't tie the XAML to the code-behind. It is possible to write an entire WPF system just as an object model, and overlay the XAML display dependant upon the object type, so the XAML becomes little more than a template. That said, doing so in not very maintainable!
The first thing that you need to realise is that the commanding model in WPF is very unlike that in Winforms development. It also, confusingly, does not inplement the command pattern. It took me a while to get my head around the new model.

You can just hook up a click event handler, but this is the worst for re-usability. To implement what you want you need to to create a Command (although there are ones "out the box" for common commands such as Copy & paste and Open). These represent the action that will be taken.

At some point in the visual tree prior to using the command, you need to create a command binding, this binds the command to the methods to be executed.

Finally you need to hook the command source (in this case, the buttons) to the Command itself.


All this can be done in XAML, but would take too long to explain here. MSDN has the usual over-complicated article here:
http://msdn.microsoft.com/en-us/library/ms752308.aspx[^]
This looks more useful:

http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900