2010-01-29 2 views
2

ElementHost 컨트롤에 대한 참조를 얻으려고합니다. 예를 들어 아래 코드에서 WPF 사용자 컨트롤의 "testImage"내용을 사용하여 이벤트를 점심을 먹어야합니다. WPF 컨트롤은 런타임에 추가되므로 ElementHost 컨트롤도 마찬가지이므로 WPF 컨트롤의 이름이나 ElementHost의 이름을 사용할 수 없습니다. 내 논리는 "testImage"부모 WPF 사용자 컨트롤을 얻고 WPF의 사용자 정의 컨트롤의 부모 ElementHost 가져올 것입니다. 하지만 코드로 작성하는 데 문제가 있습니다. 제발 조언. 감사.WPH 컨트롤의 내용 중 하나가 주어진 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

다음은 몇 가지 코드입니다. 핵심 포인트는

  • 이름 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

+0

그것은 나를 위해 일했다! 고맙습니다. 늦게 회신하지만 당신은 정말로 누군가를 도왔습니다 :) – Zer0

관련 문제