[英]C# WPF How to set MainWindow.contentControl.Content from already opened UserControl
How do I set the MainWindow.contentControl.Content from an already opened UserControl? 如何从已经打开的UserControl中设置MainWindow.contentControl.Content?
In my MainWindow I load an UserControl from where I want to override the MainWindow.contentControl.Content again but when I do so my whole menu disappears which is defined above the ContentControl :( 在我的MainWindow中,我从那里要再次覆盖MainWindow.contentControl.Content的位置加载一个UserControl,但是当我这样做时,整个菜单消失了,该菜单在ContentControl上方定义:
[CODE] MainWindow [CODE]主窗口
public MainWindow()
{
InitializeComponent();
this.contentControl.Content = new MyUserControl();
}
[XAML] MainWindow [XAML] MainWindow
<Grid>
<DockPanel>
<Menu IsMainMenu="True" DockPanel.Dock="Top">
<MenuItem Header="_Application">
</MenuItem>
</Menu>
<ContentControl x:Name="contentControl"/>
</DockPanel>
</Grid>
[CODE] MyUserControl [CODE] MyUserControl
public MyUserControl()
{
InitializeComponent();
Application.Current.MainWindow.Content = new MyUserControlNEW();
}
When you assign Application.Current.MainWindow.Content you actually remove the root Grid of your window. 分配Application.Current.MainWindow.Content时,实际上是删除窗口的根Grid。
One solution is to find the ContentControl by name like this: 一种解决方案是按如下名称查找ContentControl:
(Application.Current.MainWindow.FindName("contentControl") as ContentControl).Content = new MyUserControlNEW();
But you really should avoid manipulating controls in this way for the sake of maintainability of your code. 但是,为了确保代码的可维护性,您实际上应该避免以这种方式操纵控件。 Try to implement MVVM pattern. 尝试实现MVVM模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.