简体   繁体   English

从页面访问MainWindow的内容

[英]Access content of MainWindow from Page

I build a WPF application with MS Ribbon Menu. 我使用MS Ribbon菜单构建了WPF应用程序。 On the Main Ribbon Window I defined a frame which displays different Pages. 在主功能区窗口上,我定义了一个显示不同页面的框架。 Everything is working fine so far. 到目前为止一切正常。 When I try to get or set any value in the embeeded page I do use the following command: 当我尝试在嵌入页面中获取或设置任何值时,请使用以下命令:

Example, moving the cursor in a listview when I click on a RibbonButton in the MainWindow. 例如,当我单击MainWindow中的RibbonButton时,在列表视图中移动光标。

((Page_Rules)MainFrame.Content).lvwTemplates.Items.MoveCurrentToLast(); 

Now I try to do something vice versa, to access something in MainWindow from a page class: 现在,我尝试做一些,反之亦然,从页面类访问主窗口的内容:

((MainWindow)Content).RibbonWindow.Group_References.IsEnabled = false;

However, this isn't working. 但是,这不起作用。 I'm getting the following exception 我收到以下异常

Unable to cast object of type 'System.Windows.Controls.Grid' to type 'MyApplication.MainWindow' 无法将类型为“ System.Windows.Controls.Grid”的对象转换为类型为“ MyApplication.MainWindow”的对象

I'm wondering how I can access any control in the MainWindow from any of my embedded Pages 我不知道我怎么能在主窗口从我的任何嵌入网页的访问任何控制

You might use the VisualTreeHelper.GetParent to get the Visual Parent of your Page which is of MainWindow Type. 您可以使用VisualTreeHelper.GetParent获取MainWindow类型的Page的Visual Parent。
But note that with proper Binding, you shouldn't have to access controls directly. 但是请注意,使用适当的绑定,您不必直接访问控件。 For your cursor example, you could have a ListViewIndex integer property, this property should raise PropertyChanged on change of course, and when you click on the RibbonButton, you just have to update ListViewIndex. 对于您的光标示例,您可以具有ListViewIndex整数属性,此属性应在更改过程中提高PropertyChanged,并且当您单击RibbonButton时,只需更新ListViewIndex。 (In this case you might want to have also a readonly property giving the number of items in the list). (在这种情况下,您可能还需要一个readonly属性,该属性提供列表中的项目数)。 In your page which contains the listView, have the SelectedIndex bound to ListViewIndex and you don't have to access controls with code. 在包含listView的页面中,将SelectedIndex绑定到ListViewIndex,并且您不必使用代码访问控件。

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

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