WPF User Control and WinForm interop

hysmitht used Ask the Experts™
I have a winforms application using a ElementHost to display a WPF user control. The submit button on the WPF user control writes to a db etc. I would like it  to also fire an event on the winform such as hide form show another form. How can this be accomplished in vb.net?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Actually what you can do is raise an event in your user control and handle it onto your winform as shown below.

1) I Created a XAML user control as below.

<UserControl x:Class="WinForm_Interop.MyControl"
    Height="300" Width="300">
        <Button x:Name="CloseParent" Background="Azure" Content="WPF Close" Width="100" Height="25"></Button>

2) I created some event into to this user control

Public Sub New()
    AddHandler Me.CloseParent.Click, AddressOf CloseParent_Click
End Sub

Private Sub CloseParent_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim args As New CloseParentEventArgs()
    args.CloseParent = True
End Sub

Public Delegate Sub UserControlCloseHandler(ByVal sender As Object, ByVal e As CloseParentEventArgs)
Public Event ControlsClick As UserControlCloseHandler

Private Sub RaiseUserControlClick(ByVal e As CloseParentEventArgs)
    RaiseEvent ControlsClick(Me, e)
End Sub

Public Class CloseParentEventArgs
Private _CloseParent As Boolean
    Public Property CloseParent() As Boolean
            Return _CloseParent
        End Get
        Set(ByVal value As Boolean)
            _CloseParent = value
        End Set
    End Property
End Class

3) In my host WinForm's load event I got this control from

 and handled it's event as below.

Public Sub New()
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim x As MyControl = DirectCast(elementHost1.HostContainer.Children(0), MyControl)
    AddHandler x.ControlsClick, AddressOf x_ControlsClick
End Sub

Private Sub x_ControlsClick(ByVal sender As Object, ByVal e As MyControl.CloseParentEventArgs)
End Sub

Now what happens is when you click close button of your user control it will raise an event which will be handled in the Parent WinForm and there you can do whatever you want.

Hope it helps.
Did it help ?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial