作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我在 MainWindow.xaml 中有一个名为 MyVideoControl 的用户控件:
<Window Name="_mainWindow">
<Grid>
<MyVideoControl Name="_localVideo"/>
</Grid>
</Window>
现在用户单击一个按钮,我希望 UserControl float 在 MainWindow.xaml 之上,在一个新创建的名为 PopUp.xaml 的窗口中。
<Window Name="_popUpWindow">
<Grid>
<MyVideoControl Name="_localVideo"/>
</Grid>
</Window>
我如何完成此操作,以便移动整个对象?目前我使用 XAML 以声明方式将 MyVideoControl 放置在我的窗口中,但我猜我需要以编程方式完成所有操作?
最佳答案
是的,您可以通过从 Mainwindow
中删除 userControl
并将其作为逻辑子项添加到 PopupWin
中的任何控件来实现> 窗口。
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>
主窗口.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 在 Button_Click 上从当前 MainWindow
移除 userControl 并将其传递给 PopupWin
,在本例中是通过构造函数。
private void button1_Click(object sender, RoutedEventArgs e)
{
this.mainPanel.Children.Remove(this.myUserControl);
var wind = new PopupWin(this.myUserControl);
wind.ShowDialog();
}
注意:userControl
实例在任何时候都应该始终只是一个
元素的逻辑子元素。
关于c# - 如何将 WPF UserControl 从一个窗口移动到另一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891869/
我是一名优秀的程序员,十分优秀!