如何获取ElementHost控件,给定WPF控件的一个内容。

3
我正在尝试获取ElementHost控件的引用。例如,在下面的代码中,我需要最初使用WPF用户控件的“testImage”内容来启动事件。WPF控件是在运行时添加的,因此ElementHost控件也是如此,因此我无法使用WPF控件的名称或ElementHost的名称。 我的逻辑是获取“testImage”的父WPF用户控件,然后获取WPF用户控件的父ElementHost。 但我在编写代码时遇到了麻烦。请给予建议。谢谢。
<UserControl x:Class="WpfTest”
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300">
    <Grid>
        <Label FontSize="10" Height="24" Margin="74,16,0,0" Name="testLabel" VerticalAlignment="Top" />
        <Image Name="testImage" Stretch="Uniform" HorizontalAlignment="Left" Width="64" Height="81" VerticalAlignment="Top" Margin="8,0,0,0"/>
    </Grid>
</UserControl>
1个回答

2

以下是一些可能会对你有所帮助的代码。关键点如下:

  • 在运行时创建ElementHost时为其命名
  • 使用查找WPF树中所需控件的帮助函数FindVisualChildByName()

希望这能帮到你!

  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim ElementHost1 As New System.Windows.Forms.Integration.ElementHost
        Dim WpfTest1 As New WindowsApplication1.WPFTest

        ElementHost1.Dock = DockStyle.Fill
        ElementHost1.Name = "ElementHost1"
        ElementHost1.Child = WpfTest1

        Me.Controls.Add(ElementHost1)
    End Sub

    Private Sub GetImageReference_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ElementHost1 As System.Windows.Forms.Integration.ElementHost = Me.Controls("ElementHost1")
        Dim TheGrid As System.Windows.Controls.Grid = CType(ElementHost1.Child, WPFTest).MyGrid
        Dim ImageTest As System.Windows.Controls.Image = FindVisualChildByName(TheGrid, "testImage")
        Stop
    End Sub

    Public Function FindVisualChildByName(ByVal parent As System.Windows.DependencyObject, ByVal Name As String) As System.Windows.DependencyObject
        For i As Integer = 0 To System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent) - 1
            Dim child = System.Windows.Media.VisualTreeHelper.GetChild(parent, i)
            Dim controlName As String = child.GetValue(System.Windows.Controls.Control.NameProperty)
            If controlName = Name Then
                Return child
            Else
                Dim res = FindVisualChildByName(child, Name)
                If Not res Is Nothing Then
                    Return res
                End If
            End If
        Next
        Return Nothing
    End Function

它对我有用!谢谢你。回复晚了但你确实帮助了某人 :) - Zer0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接