return 使用 .Child 添加 UserControl 后到 MainWindow
return to MainWindow after using adding a UserControl with .Child
在 MainWindow.xaml.cs
中,我使用 .Child 切换到 userControl,如下所示:
Grid1.Visibility = Visibility.Hidden;
Stage.Child = new UserControlName();
其中 Grid1
是内容位于主 window 中的网格(应该隐藏,因为有些内容会从用户控件后面窥视),并且 Stage
是一个 border
元素,我希望 UserControl 在其中填充
<Grid >
<Border x:Name="Stage" Grid.RowSpan="4" Grid.ColumnSpan="2"/>
<Grid x:Name="Grid1" FocusManager.FocusedElement="{Binding ElementName=textBox}" Margin="10,10,10,10" Width="1200" Height="649" >
如何从它自己的 xaml.cs
文件中关闭或隐藏 UserControlName
,以及如何将视图返回到主 window,同时返回 MainWindow
的 Grid1
到 Visible
?
我会使用 PRISM (https://msdn.microsoft.com/en-us/library/ff921098(v=pandp.40).aspx) 中的区域来实现它。但是,如果您创建了简单的应用程序并且不想花时间学习 PRISM,您可以例如通过添加 MainWindow 类型的参数来扩展 UserControlName class 的构造函数,并在此对象上调用一些将视图更改为的方法你的愿望状态。
难看的代码示例:
主窗口:
private void Button_Click(object sender, RoutedEventArgs e)
{
grid1.Visibility = Visibility.Hidden;
br.Child = new UserControl2(this);
}
public void CloseView()
{
grid1.Visibility = Visibility.Visible;
br.Child = null;
}
用户控件:
private MainWindow window;
public UserControl2(MainWindow window)
{
this.window = window;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
window.CloseView();
}
另一种选择是使用(例如)Mvvm Light 工具包和消息传递 (https://msdn.microsoft.com/en-us/magazine/jj694937.aspx)。
child 视图将发送一条消息以关闭,主 window 将收到此消息并隐藏网格。
优点是主 window 和 child 控件仍然是分离的,这意味着 child 不需要知道主 window 的任何信息。
抓住这个机会,花些时间在 Mvvm 模式和 Mvvm light 等库中。
在 MainWindow.xaml.cs
中,我使用 .Child 切换到 userControl,如下所示:
Grid1.Visibility = Visibility.Hidden;
Stage.Child = new UserControlName();
其中 Grid1
是内容位于主 window 中的网格(应该隐藏,因为有些内容会从用户控件后面窥视),并且 Stage
是一个 border
元素,我希望 UserControl 在其中填充
<Grid >
<Border x:Name="Stage" Grid.RowSpan="4" Grid.ColumnSpan="2"/>
<Grid x:Name="Grid1" FocusManager.FocusedElement="{Binding ElementName=textBox}" Margin="10,10,10,10" Width="1200" Height="649" >
如何从它自己的 xaml.cs
文件中关闭或隐藏 UserControlName
,以及如何将视图返回到主 window,同时返回 MainWindow
的 Grid1
到 Visible
?
我会使用 PRISM (https://msdn.microsoft.com/en-us/library/ff921098(v=pandp.40).aspx) 中的区域来实现它。但是,如果您创建了简单的应用程序并且不想花时间学习 PRISM,您可以例如通过添加 MainWindow 类型的参数来扩展 UserControlName class 的构造函数,并在此对象上调用一些将视图更改为的方法你的愿望状态。 难看的代码示例:
主窗口:
private void Button_Click(object sender, RoutedEventArgs e)
{
grid1.Visibility = Visibility.Hidden;
br.Child = new UserControl2(this);
}
public void CloseView()
{
grid1.Visibility = Visibility.Visible;
br.Child = null;
}
用户控件:
private MainWindow window;
public UserControl2(MainWindow window)
{
this.window = window;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
window.CloseView();
}
另一种选择是使用(例如)Mvvm Light 工具包和消息传递 (https://msdn.microsoft.com/en-us/magazine/jj694937.aspx)。
child 视图将发送一条消息以关闭,主 window 将收到此消息并隐藏网格。
优点是主 window 和 child 控件仍然是分离的,这意味着 child 不需要知道主 window 的任何信息。
抓住这个机会,花些时间在 Mvvm 模式和 Mvvm light 等库中。