更新时间:2023-10-11 13:49:46
是的,你可以通过删除用户控件
从主窗口
做到这一点,将其添加为一个逻辑孩子任何的控制在 PopupWin
窗口。
Yes you can do this by removing the userControl
from the Mainwindow
and adding it as a logical child to any of the control in the PopupWin
window.
的 UserControl.xaml:的
UserControl.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:的
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:的
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:的揭露一个新的构造接受用户控件
并将其添加为一个孩子的的mainPanel
PopupWin.xaml.cs: Expose a new constructor to accept userControl
and add it as a child to the 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 的在Button_Click从目前的主窗口
删除用户控件,并把它传递给 PopupWin
,在这种情况下,通过构造。
MainWindow.xaml.cs On Button_Click remove the userControl from the current MainWindow
and pass it to PopupWin
, in this case via constructor.
private void button1_Click(object sender, RoutedEventArgs e)
{
this.mainPanel.Children.Remove(this.myUserControl);
var wind = new PopupWin(this.myUserControl);
wind.ShowDialog();
}
的 注意:的在用户控件
实例应该永远只有有一个
元素的逻辑子在任何时候。
Note: The userControl
instance should always be a logical child of only one
element at anytime.