wlamers
wlamers

Reputation: 1286

How to access a control on another window

After a couple of hours searching to a solution I need some help.

I have a WPF application with a main window and a second window using the RibbonWindow class. The problem is that I am not able to access a control (datagrid) on the MainWindow from a second window. The second window is called (and in the class) CanSubMessages. MainWindow inherits from RibbonWindow and CanSubMessages from Window.

The thing I try to achieve is an updated of the datagrid on MainWindow from the CanSubMessages window. Sounds simple right?

I do the following from CanSubMessages:

Window rootWindow = Application.Current.MainWindow as Window;
rootWindow.CanDataGridMessagesCh1.Items.Refresh();

And CanDataGridMessagesCh1 is a datagrid in the MainWindow. It's name is given in the corresponding XAML with:

<DataGrid x:Name="CanDataGridMessagesCh1" AutoGenerateColumns="False" ...

I don't see why this control isn't accesible. This is the error I get:

'System.Windows.Window' does not contain a definition for 'CanDataGridMessagesCh1' and no extension method 'CanDataGridMessagesCh1' accepting a first argument of type 'System.Windows.Window' could be found (are you missing a using directive or an assembly reference?)

Anybody a clue?

Upvotes: 2

Views: 2905

Answers (1)

Dean Chalk
Dean Chalk

Reputation: 20481

this line is wrong:

Window rootWindow = Application.Current.MainWindow as Window; 

should be

Window rootWindow = Application.Current.MainWindow as MyWindowClass; 

EDIT

An alternative solution would be include a reference to your main window in your child window:

Here is an example assuming that you are creating your child window from your main window, and that youve added the main window type into your child window constructor

ChildWindow cw = new ChildWindow(this);

and then later in your child window:

var mainwindow = this.MainWindow; // from the constructor

Upvotes: 1

Related Questions