简体   繁体   English

C#WPF userControl将数据发送到mainWindow textBlock on ButtonClick

[英]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. 所有这些示例都是相反的,因为这应该是UserControl工作方式。

A UserControl is a packaged piece of re-usable functionality. UserControl是打包的可重用功能。 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. 相反,您应该在UserControl公开路由事件,以选择诸如“何时”号之类的内容,并在主窗口中对其进行订阅。

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. 如果您的MainWindow.xaml具有UserControl并且您想对MainWindow.xaml.cs文件中控件的更改做出反应,则可以在UserControl代码后面添加一个delegate ,并在MainWindow.xaml.cs为其注册一个处理程序。 MainWindow.xaml.cs文件。 Implementing new delegate s are generally somewhat simpler than implementing RoutedEvent s, which is another way that you could handle this situation. 实现新的delegate通常比实现RoutedEvent更为简单,这是您可以处理这种情况的另一种方法。

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. 使用这样的delegate将使您能够有效地从后面的子UserControl代码向主视图传递信号,您可以以任何想要的方式对其进行响应。 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. 在Stack Overflow上的此处发布有关如何实现此目标的完整详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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