L.Persad
L.Persad

Reputation: 47

How to disable a user control on main window from page WPF

I have a user control sitting on my main window, It is a menu.

When a user tries editing objects on a page I want to disable this user control while the user is on edit mode so they do not navigate off the page they are editing.

I am having trouble accessing the user control(placed on the main window) from a page

User Control Name - MenuView

The code below is on the page load of the page

MainWindow mainWindow = new MainWindow();
mainWindow.MenuView.IsEnabled = false;

This does not seem to work though

Upvotes: 1

Views: 401

Answers (1)

mm8
mm8

Reputation: 169150

You need to get a reference to the existing instance of the MainWindow instead of creating a new one.

If you don't care about MVVM, the easiest way to do this would probably be to use the static Application.Current.Windows or App.Current.MainWindow property:

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault(); 
if (mainWindow != null)
    mainWindow.MenuView.IsEnabled = false;

Note that this approach does create a coupling between your classes, but this is inevitable if you access a field of the window from in the Page class.

You probably want to look into the MVVM design pattern but that's another story.

Upvotes: 1

Related Questions