Eric after dark
Eric after dark

Reputation: 1808

How to set the contents of a DataGrid in a ViewModel

I am moving a DataGrid from code-behind into a ViewModel-UserControl structure. When in code-behind, the settings of my DataGrid are set like so...

public Window1()
{
     setDataGrid();
}

public class Data
{
     public int inOutNum { set; get; }
     public string input { set; get; }
     public string output { set; get; }
}

public static void setDataGrid()
{
     //Query for Window1
     var mainWindow = Application.Current.Windows
         .Cast<Window1>()
         .FirstOrDefault(window => window is Window1) as Window1;

     for (int i = 1; i <= 16; i++)
     {
         mainWindow.dataGrid.Items.Add(new Data() { inOutNum = i - 1, input = "", output = ""});
     }
}

<DataGridTextColumn Binding="{Binding Path=inOutNum}" Width="15" />
<DataGridTextColumn Binding="{Binding Path=input}" Header="Inputs" Width="160" />
<DataGridTextColumn Binding="{Binding Path=output}" Header="Outputs" Width="160" />

When switching to the View Model structure I want to move away from using the window query that I used above (because I'm guessing it is the wrong way to work with the grid). When I put the above c# code into a ViewModel, the program can't see the DataGrid in the loop where I add contents. How can I change the code that I have so that it correctly adds to my DataGrid in it's new location?

Upvotes: 0

Views: 126

Answers (1)

Andrew
Andrew

Reputation: 1492

You should create a ViewModel class for your window which contains a collection (usually an ObservableCollection) or your Data objects. Then, to hook them up you need to set the DataContext of your Window to the new ViewModel class, and set the ItemsSource of your DataGrid to the ObservableCollection

Upvotes: 1

Related Questions