当前位置: 首页 > 编程语言 > C#

从用户控件访问父窗口share

时间:2023-04-11 00:40:51 C#

从用户控件访问父窗口我正在尝试从用户控件访问父窗口。userControl1uc1=newuserControl1();mainGrid.Children.Add(uc1);使用此代码,我将userControl1加载到主网格。但是当我在userControl1上单击一个按钮时,我想将另一个userControl2加载到主窗口的mainGrid中?你试过WindowyourParentWindow=Window.GetWindow(userControl1);这将获得根级窗口:WindowparentWindow=Application.Current.MainWindow或直接父窗口WindowparentWindow=Window.GetWindow(this);建议的唯一原因是WindowyourParentWindow=Window.GetWindow(userControl1);不适合你,因为你没有将它转换为正确的类型:varwin=Window.GetWindow(this)asMyCustomWindowType;if(win!=null){win.DoMyCustomWhatEver()}else{ReportError("运气不好,此控件仅适用于MyCustomWindowType的后代");除非你的窗口和你的控件之间必须有更多的耦合,否则我认为你的方法设计得很糟糕。我建议传递网格,控件将作为构造函数参数运行,作为属性或在任何Window上动态搜索适当的(根?)网格。谢谢你帮助我们。我有另一个解决方案((this.Parent)asWindow).Content=newuserControl2();这完美地工作修改UserControl的构造函数以接受MainWindow对象作为参数。然后在MainWindow中创建时将MainWindow对象传递给UserControl。MainWindowpublicMainWindow(){InitializeComponent();userControl1uc1=newuserControl1(this);}UserControlMainWindowmw;publicuserControl1(MainWindowrecievedWindow){mw=recievedWindow;}UserControl中的示例事件privatevoidButton_Click(objectsender,RoutedEventArgse){mw.mainGrid.Children.Add(this);}创建主窗口的静态实例,您只需在用户控件中调用它:参见此示例:Window1.cspublicpartialclassWindow1:Window{publicWindow1(){InitializeComponent();_Window1=这个;}publicstaticWindow1_Window1=newWindow1();}UserControl1.CS以上就是C#学习教程:从用户控件访问父窗口共享的所有内容,如果对大家有用需要进一步了解C#学习教程,希望大家多多关注-publicpartialclassUserControl1:UserControl{publicUserControl1(){InitializeComponent();}privatevoidAddControl(){Window1._Window1.MainGrid.Children.Add(usercontrol2)}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: