【发布时间】:2015-04-22 23:13:09
【问题描述】:
想象下一种情况:我确实有一个应用程序窗口,里面有几个用户控件。它们过去并排显示,但现在我想在弹出窗口中显示其中一个。不在 Popup 控件中,而是在新窗口中。
查看示例 XAML:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication3="clr-namespace:WpfApplication3"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<wpfApplication3:UserControl1 Visibility="Hidden"
x:Name="UserControl1"/>
<Button Click="ButtonBase_OnClick"
Width="100"
Height="60">open window</Button>
</Grid>
在后面的代码中,我需要从当前窗口中分离用户控件并分配给新窗口:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var parent = VisualTreeHelper.GetParent(UserControl1);
if (parent != null)
{
parent.RemoveChild(UserControl1);
}
var w = new Window
{
Content = UserControl1,
Title = "sample",
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.CanResize
};
w.Show();
}
在调用 w.Show() 之后,我总是得到空白的白色窗口。
如果在按钮单击处理程序中发生变化
内容 = UserControl1
到
内容 = new UserControl1()
我也会得到正确的内容。 但我不能使用这种方式,因为我想在弹出和弹出事件期间保持我的用户控件状态。 那么如何在新窗口中显示现有的用户控件而不重新创建它呢?
【问题讨论】:
标签: c# wpf xaml user-controls