I'm new to C#, and I'm new to the idea of "partial" classes.
I wish to access the "grid" variable outside of this "MainWindow" class. How would I go about doing that?
I'm new to C#, and I'm new to the idea of "partial" classes.
I wish to access the "grid" variable outside of this "MainWindow" class. How would I go about doing that?
Partial means that your class is split among different files, it has nothing to do with the exposure of variables to other classes.
Your grid is a local variable in your current method, so it's not accessible by others. If you want to make it accessible, define it as a property instead.
public DataGrid Grid { get; set; }
Even though it is technically possible, you should not make your data grid accessible outside the class. The grid is part of the view managed by your class, so making the grid accessible to other classes breaks encapsulation by making implementation details of your form visible.
I have another class,
Server
, and it receives data that I wish to add togrid.ItemSource
.
Then your Server
class should provide a data source to which your form should bind the grid. In other words, the access should go in the other direction.
You need to declare the variable as a public member of the class like this
public partial class MainWindow ...
{
public DataGrid grid;
public MainWindow()
{
...
}
public void DataGrid_Loaded(...)
{
...
grid = sender as DataGrid;
...
}
}
Now you can access to the variable in this way
var x = MainWindow.grid;