如何从WindowsFormsHost获取子控件属性?WPF空引用异常求助
问题原因及解决办法
动态创建的WindowsFormsHost仅设置.Name属性不会自动加入WPF元素的名称范围(Name Scope),导致FindName方法无法找到目标控件,返回Nothing,进而触发空引用异常。
解决方式
1. 注册名称到元素的名称范围
在将WinHost添加到Grid前,调用RegisterName把它注册到EmailSend_Grid的名称范围中:
Dim WinHost As New WindowsFormsHost With WinHost .Name = "WinHost" .Child = HTMLEditor End With Grid.SetRow(WinHost, 5) EmailSend_Grid.RegisterName(WinHost.Name, WinHost) ' 新增注册名称的代码 EmailSend_Grid.Children.Add(WinHost)
2. 直接保留控件引用
在类级别声明变量存储控件实例,后续直接访问即可,避免查找失败:
' 类级别声明变量 Private WinHost As WindowsFormsHost Private HTMLEditor As HTMLEditControl ' 创建控件的代码 HTMLEditor = New HTMLEditControl With HTMLEditor .Name = "EmailSend_Editor" .EnableInlineSpelling = True End With WinHost = New WindowsFormsHost With WinHost .Name = "WinHost" .Child = HTMLEditor End With Grid.SetRow(WinHost, 5) EmailSend_Grid.Children.Add(WinHost) ' 后续直接访问变量 Dim targetEditor = HTMLEditor
3. 遍历子元素查找控件
如果无法保留引用,可通过遍历Grid的子元素定位目标:
Dim WinHost As WindowsFormsHost = EmailSend_Grid.Children.OfType(Of WindowsFormsHost)().FirstOrDefault(Function(w) w.Name = "WinHost") If WinHost IsNot Nothing Then Dim HTMLEditor As HTMLEditControl = CType(WinHost.Child, HTMLEditControl) ' 执行后续操作 End If
内容的提问来源于stack exchange,提问作者gchq
相关产品推荐
相关产品推荐

