Sol
Sol

Reputation: 53

Using a reference to the main Window from a static class - Good practice?

I have a WPF application with the main Window class called MainWindow. Since I have other classes that need to access the Dispatcher of the UI thread to update bounded lists, I found this solution:

I made a static class:

 static class UI 
    {
        static public MainWindow window;
    }

And added the following line in the app constructor:

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            UI.window = this;
...

Now I can access the components of my GUI everywhere by using UI.window.Dispatcher.Invoke().

The question is - is this a good programming practice? Is there a better method of doing so?

Thank you

Update:

I seem to get the exception thrown only when I update an ObservableCollection which is bound to a 3rd party control. I have another static OC bound to a listbox (to display updated messages) and I can update that one from other threads without using the dispatcher. How come? Is it because its a static OC or is it related to the control?

Upvotes: 3

Views: 2089

Answers (3)

Matěj Zábský
Matěj Zábský

Reputation: 17272

If its only about the dispatcher, you can do this

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (Action)delegate()
    {
    });

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1063338

In the general case, it isn't ideal - static has some gotchas if you expect threads to be independent, or if you expect garbage collection to collect the window - but arguably you can probably get away with it for you main window, since that is probably essentially singleton and lasts the lifetime of the app.

Personally I probably wouldn't - I'd pass it in via a property or constructor argument - but I'm a bit fussy.

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564641

Since I have other classes that need to access the Dispatcher of the UI thread to update bounded lists

Personally, if you need this, I would just save a reference to the Dispatcher, not to the entire UI.

Providing a reference to the Window itself could, potentially, cause confusion. The intent here is not as clear.

Upvotes: 4

Related Questions