是的,您可以通过从userControl
中删除Mainwindow
并将其作为逻辑子项添加到PopupWin
窗口中的任何控件来执行此操作。
用户控件.xaml:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="100">
<Grid>
<TextBox x:Name="txtBlock1" Text="hai"/>
</Grid>
</UserControl>
MainWindow.xaml :
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" Height="550" Width="555">
<Grid>
<StackPanel x:Name="mainPanel" Orientation="Vertical ">
<Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
<WpfApplication1:UserControl1 x:Name="myUserControl" />
</StackPanel>
</Grid>
</Window>
PopupWin.xaml:
<Window x:Class="WpfApplication1.PopupWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PopupWin" Height="300" Width="300">
<StackPanel x:Name="mainPanel"/>
</Window>
PopupWin.xaml.cs:公开一个新的构造函数以接受userControl
并将其作为子项添加到mainPanel
public partial class PopupWin : Window
{
public PopupWin()
{
InitializeComponent();
}
private UserControl control;
public PopupWin(UserControl control)
: this()
{
this.control = control;
this.mainPanel.Children.Add(this.control);
}
}
MainWindow.xaml.cs On Button_Click 从当前删除 userControlMainWindow
并将其传递给PopupWin
,在本例中是通过构造函数。
private void button1_Click(object sender, RoutedEventArgs e)
{
this.mainPanel.Children.Remove(this.myUserControl);
var wind = new PopupWin(this.myUserControl);
wind.ShowDialog();
}
注意:实例userControl
都应该是唯一one
元素的逻辑子元素。