简体   繁体   English

从用户控件访问父窗口中的WPF元素

[英]Accessing the WPF element in parent window from the user control

I have a custom menu control in the main window of my WPF application. 我在WPF应用程序的主窗口中有一个自定义菜单控件。 In main window, I have a frame. 在主窗口中,我有一个框架。 I want to change the page in this frame based on the selection in the custom menu control. 我想根据自定义菜单控件中的选择来更改此框架中的页面。 Below is the code I tried. 下面是我尝试的代码。

    Private Sub NominationMenuItem_Click(sender As Object, e As RoutedEventArgs)
    Dim parentWindow As Window
    parentWindow = Application.Current.MainWindow
    parentWindow.MainFrame.Navigate(New NominationSearch)
End Sub

I know that I can't directly access "MainFrame" control using the "parentWindow" object. 我知道我无法使用“ parentWindow”对象直接访问“ MainFrame”控件。 How do I rewrite the last line to get a reference to the existing frame object. 我如何重写最后一行以获得对现有框架对象的引用。

It's not appropriate for UserControl to manipulate it's parent. UserControl不适合操纵其父项。 You should let your MainWindow to listen for NominationMenuItem changes via events and then MainWindow itself do the navigation. 您应该让MainWindow通过事件侦听NominationMenuItem更改,然后MainWindow自己进行导航。

So first you need to define an event in your UserControl : 因此,首先您需要在UserControl定义一个事件:

Public Event NominationMenuItemChanged As RoutedEventHandler

Private Sub NominationMenuItem_Click(sender As Object, e As RoutedEventArgs)
    RaiseEvent NominationMenuItemChanged(Me, New RoutedEventArgs())
End Sub

And then listen to this event in your MainWindow : 然后在您的MainWindow监听此事件:

Public Sub MainWindow()
    AddHandler MyUserControl.NominationMenuItemChanged, AddressOf UC_NominationMenuItemChanged
End Sub

Private Sub UC_NominationMenuItemChanged(sender As Object, e As RoutedEventArgs)
    MainFrame.Navigate(MyUserControl.NominationSearch)
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM