2010-01-29 189 views
2

我想获得对ElementHost控件的引用。例如,在下面的代码中,我需要最初使用WPF用户控件的“testImage”内容来为事件提供午餐。 WPF控件在运行时添加,ElementHost控件也添加了,所以我不能使用WPF控件的名称或ElementHost的名称。 我的逻辑是获取“testImage”的父级WPF用户控件,然后获取WPF用户控件的父级ElementHost。 但我有麻烦写在代码中。请指教。谢谢。如何获取ElementHost控件,给定WPF控件的内容

<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

以下是一些可能对您有帮助的代码。其要点是:

  • 名称ElementHost的,当你在运行时创建它
  • 利用帮助功能FindVisualChildByName()来搜索WPF树以获得所需的控制

希望这有助于!

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 
+0

谢谢,我会试试看。我会让知道它是否有帮助。 – Serg 2010-01-29 21:57:35

+0

它为我工作!谢谢。晚回复,但你真的帮助了一个人:) – Zer0 2014-11-18 22:49:53