WPF框架访问父页面控件[英] WPF Frame accessing parent page controls













我更喜欢的设计模式(许多开发人员也是如此)是将数据库的处理和业务逻辑隔离到一个或多个类中,并具有一个简单的程序化接口,可以轻松测试. GUI组件保持尽可能简单和薄,因此必要时可以轻松更改它们.这通常称为模型视图控制器模式,但还有其他名称.在您的示例中,封装您的业务逻辑的"控制器"类将具有读取和设置信息的属性和方法,以及写入数据库更改的"保存"或" commit"方法.保存完成后,它将引发一个"保存"或"更改"的事件,该事件通知所有控件("视图"),显示信息已更改的信息,它们会根据您的控制器类的属性的新值来刷新自己.



I have a WPF page that contains a Listbox and a frame. The frame has various pages loaded into it determined by the selection within the Listbox.

Each page within the frame has a variety of different input boxes and has a Save Cancel button. When the Save button is clicked I need the content to be saved to the database and the Listbox in the parent page to be refreshed to reflect the new data.

Saving the data is easy but how do I initiate a refresh on the contents of the Listbox in the parent page when calling it from the page that inside the frame?

I need to somehow be able to access the parent pages controls to do this.

Any ideas?


It is technically possible to reach up into the parent control and have your way with the controls it contains, but it makes for code that's very difficult to maintain because if you change the structure of the parent control, you break code in all of the contained pages. That would be considered a very tightly-coupled design and it's often fragile.

A somehwat cleaner design would be to have your page classes raise an event when the Save button is pressed. Then your parent frame can sink the event and refresh whatever it knows needs to be refreshed after a save operation. That's easier to maintain because your components are more loosely coupled, but it still puts a lot of database knowledge into your GUI components. Such a design might be appropriate for a relatively simple app on which you don't expect to do a lot of maintenance or future enhancements.

The design pattern I prefer (as do many developers) is to isolate the database handling and business logic inside one or more classes with a simple programmatic interface that can be tested easily. The GUI components are kept as simple and thin as possible, so they can be easily changed if necessary. This is often called a Model-View-Controller pattern but there are other names for it. In your example, the "controller" class that encapsulates your business logic would have properties and methods for reading and setting information, and a "Save" or "Commit" method that writes changes to a database. Once the save is complete it would raise a "Saved" or "Changed" event that notifies all controls ("views") displaying information that the information has changed and they would refresh themselves based on the new values of the properties of your controller class.