简体   繁体   中英

Updating GUI Component from a different class C# WPF

I am trying to update a GUI component (DataGrid) in one class from a different class. I am using C# and WPF Forms.

When I used the standard WF forms I could pass a reference to the GUI component as a parameter to the function that needed to do the work with the DataGrid. However, I do not know how I can do this in WPF.

I have Class1 which has the GUI component and I need Class3 to run the function inside Class2 which will automatically update the GUI display of the Datagrid found in Class1.

Typically in WPF you'd use WPF databinding to bind the grid to an object implementing one of the "observable" classes/interfaces such as INotifyPropertyChanged or ObservableCollection<> . That way you can work with the data as objects, and the databinding will ensure those changes are reflected in the grid.

If you're not ready to use databinding and want to do things the hard way, you can. You just do the same thing you would have done in WinForms. I'm not sure what problem you're having, but from what you described:

public class Class3 {
    public void RunTheFunctionInClass2(Class1 window, Class2 class2) {
        class2.TheFunction(window.TheDatagrid);
    }
}

And in Class1.xaml:

<DataGrid Name="TheDataGrid" ... />

This assumes that Class1 and Class3 are both in the same assembly -- by default, the TheDataGrid field will have internal visibility.

I found out how I can pass the WPF datagrid as a parameter. It is in the same way as WF the only problem is I wasn't importing the required element for the WPF DataGrid.

The import required was

using Microsoft.Windows.Controls

Using the above the import allows access to the DataGrid so you can perform the following

private void myMethod(DataGrid myTable){}

Thanks everyone for the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM