我有一个用户控件,我将其加载到MainWindow
在运行时。我无法从包含窗口获取句柄UserControl
.
我努力了this.Parent
,但它始终为空。有谁知道如何从 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);
The GetWindow
方法将为您遍历 VisualTree 并找到托管控件的窗口。
您应该在加载控件后运行此代码(而不是在 Window 构造函数中)以防止GetWindow
返回方法null
。例如。连接一个事件:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)