简体   繁体   中英

C# WPF userControl to send data to mainWindow textBlock on buttonClick

I am trying to create a simple onscreen keypad created using buttons (currently a User-control) , on those buttons i have a click event, when i click/touch a button i want the value of that button sent to a Text-block in my Main-window.

I can't/don't understand how to make the User-control (keypad) see the Text-block (in Main-window) to add in the value that i need.

I have seen solutions that use command Bindings and solutions that use the visual tree traversing but all of them are the main window accessing the user control, not the other way around.

All the examples are the other way around because that is how a UserControl is supposed to work.

A UserControl is a packaged piece of re-usable functionality. It should not know anything about the code that is using it.

Instead you should expose routed events in your UserControl for things like a when number was selected, and subscribe to them in your main window.

There are many ways to achieve what you want. If your MainWindow.xaml has a UserControl and you want to react to a change from the control in the MainWindow.xaml.cs file, then you could add a delegate to the UserControl code behind and register a handler for it in the MainWindow.xaml.cs file. Implementing new delegate s are generally somewhat simpler than implementing RoutedEvent s, which is another way that you could handle this situation.

Using a delegate like this will enable you to effectively pass a signal to the main view from the child UserControl code behind, which you can react to in any way you want to. Rather than explain the whole story again here, please see my answers from the Passing parameters between viewmodels and How to call functions in a main view model from other view models? posts here on Stack Overflow for full details on how to achieve this.

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