开发者

Passing a value from a WPF page to its parent's window

I am hoping for some guidence. I have a wpf application that contains a window (Window1) and a page (Page1). The page is inside the window using a frame.

I have a button within the page that I want to be able to press and pass a string value back to mainwindo开发者_运维知识库w and display it within a label.

Can anyone help with a basic example as I have no clue!


Generally speaking, it sounds like you need a publisher/subscriber pattern eventing service of some sort in your application. This would be a Singleton object that your outer window could subscribe to. A general call to this service might look something like:

EventService.Instance.AddListener( "TheEventICareAbout"
            , delegate( possiblySomeParameters ) {
                //Do Interesting Stuff Here.  This code can access members of your
                //window class or call methods on it to react to the event.
                } ) ;

Then your child page could raise some event on the service:

EventService.Instance.RaiseEvent("TheEventICareAbout"
            , new EventParameters( possiblySomeParameters ) ) ;

Internally, the service is probably just a dictionary of event names and framework events. Your AddListener would check to see if the event name existed already and, if so, add the new delegate to the event. If not, it would create a new entry in the dictionary and store the new delegate as in the event.

Most of the application frameworks wind up using this pattern at some point, so I'm sure there are plenty of options out there if you don't want to write your own. Take a look at the Prism Event Aggregator. This is a short introduction, but the basic format is going to remain the same regardless of if you write it yourself or if you grab a pre-existing solution.

The basic advantages of this approach are loose coupling and extensibility. It also lends itself well to the MVVM architecture, where your ViewModel could raise the event for other ViewModels to react to. This lets you get your business logic out of your View and into someplace where you can test it more completely.

Although I wouldn't recommend it, another option for a "quick and dirty" solution is to add an event to your Page and have the Window add a handler to it. The Page can then raise this custom event. The things you want to be careful about here are garbage collection (your page may not get GCed if you don't remove the handler properly) and ensuring that you don't wind up with many pages, each of which raises a slightly different event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜