我有一个用户控件,可以在运行时加载到MainWindow
中。我无法从UserControl
获取包含窗口的句柄。
我已经尝试过this.Parent
,但始终为null。有谁知道如何从WPF中的用户控件获取包含窗口的句柄?
这是控件的加载方式:
private void XMLLogViewer_MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem application = sender as MenuItem;
string parameter = application.CommandParameter as string;
string controlName = parameter;
if (uxPanel.Children.Count == 0)
{
System.Runtime.Remoting.ObjectHandle instance = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, controlName);
UserControl control = instance.Unwrap() as UserControl;
this.LoadControl(control);
}
}
private void LoadControl(UserControl control)
{
if (uxPanel.Children.Count > 0)
{
foreach (UIElement ctrl in uxPanel.Children)
{
if (ctrl.GetType() != control.GetType())
{
this.SetControl(control);
}
}
}
else
{
this.SetControl(control);
}
}
private void SetControl(UserControl control)
{
control.Width = uxPanel.Width;
control.Height = uxPanel.Height;
uxPanel.Children.Add(control);
}
最佳答案
尝试使用以下内容:
Window parentWindow = Window.GetWindow(userControlReference);
GetWindow
方法将为您遍历VisualTree并找到承载控件的窗口。您应该在控件加载后(而不是在Window构造函数中)运行此代码,以防止
GetWindow
方法返回null
。例如。整理一个事件:this.Loaded += new RoutedEventHandler(UserControl_Loaded);