简体   繁体   English

如何从用户控件 WPF C# 访问父 window 中的按钮

[英]How to access a button in the parent window from user control WPF C#

In my MainWindow ,在我的MainWindow中,

  • I have a button btnMainMenu我有一个按钮btnMainMenu
  • I have a user control NavigationWindow我有一个用户控件NavigationWindow

from the user control, I want to change the visibility of the btnMainMenu form the MainWindow .从用户控件中,我想更改btnMainMenu表单MainWindow的可见性。 I have tried most of the steps suggested in other posts but none of them seems to work for me.我已经尝试了其他帖子中建议的大部分步骤,但它们似乎都不适合我。

I tried this line of code but got error.我尝试了这行代码但出错了。

System.Windows.Controls.Button btn = (this.Parent as MainWindow).Controls["btnMainMenu"] as Button;

I would recommend to please go through some design patterns.我建议通过一些设计模式取悦 go。 This is not supposed to be a recommended way to get an object and changed the visibility.这不应该是获得 object 并更改可见性的推荐方法。

Have a view and a view model make some dependency and change some property of view model.有一个视图和一个视图 model 建立一些依赖关系并更改视图 model 的某些属性。

Just for your learning, I can tell you one of the way but definitely would not recommend it in your product.只是为了您的学习,我可以告诉您一种方法,但绝对不会在您的产品中推荐它。

You can use recursion on the child controls of the parent control till you find out the button control you need.您可以在父控件的子控件上使用递归,直到找到所需的按钮控件。

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

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