我有一个在运行时加载到 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);
关于c# - WPF 用户控件父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/302839/