bzsparks
bzsparks

Reputation: 39

WPF Binding a List to a DataGrid

This is my first time working with a WPF datagrid. From what I understand I am supposed to bind the grid to a public propery in my viewmodel. Below is the ViewModel code, as I step through the debugger GridInventory is getting set to List containing 2606 records however these records never show in the datagrid. What am I doing wrong?

public class ShellViewModel : PropertyChangedBase, IShell
{
    private List<ComputerRecord> _gridInventory;

    public List<ComputerRecord> GridInventory
    {
        get { return _gridInventory; }
        set { _gridInventory = value; }
    }

    public void Select()
    {
        var builder = new SqlConnectionBuilder();
        using (var db = new DataContext(builder.GetConnectionObject(_serverName, _dbName)))
        {
            var record = db.GetTable<ComputerRecord>().OrderBy(r => r.ComputerName);                
            GridInventory = record.ToList();
        }
    }
}

My XAML is

<Window x:Class="Viewer.Views.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="InventoryViewer" Height="647" Width="1032" WindowStartupLocation="CenterScreen">
<Grid>
    <DataGrid x:Name="GridInventory" ItemsSource="{Binding GridInventory}"></DataGrid>
    <Button x:Name="Select" Content="Select" Height="40" Margin="600,530,0,0" Width="100" />
</Grid>
</Window>

Upvotes: 0

Views: 1907

Answers (4)

user2391685
user2391685

Reputation: 1066

You might want to consider using bind ObservableCollection to the datagrid. Then you don't need to maintain a private member _gridInventory and a public property GridInventory

//viewModel.cs
public ObservableCollection<ComputerRecord> GridInventory {get; private set;}
//view.xaml
<DataGrid ... ItemsSource="{Binding GridInventory}" .../>

Upvotes: 0

David Bekham
David Bekham

Reputation: 2175

I think you should use the RaisePropertyChanged in the ViewModel and Model and also should set the DataContext in the View.

<Window.DataContext>    
    <local:ShellViewModel />    
</Window.DataContext>

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31576

The page's datacontext is not bound to an instance of the View Model. In the code behind after the InitializeComponent call, assign the datacontext such as:

InitializeComponent();

DataContext = new ShellViewModel();

Upvotes: 0

uowzd01
uowzd01

Reputation: 1000

i think you need call raisepropertychanged event in your GridInventory setter so that view can get notified.

public List<ComputerRecord> GridInventory
{
    get { return _gridInventory; }
    set 
    { _gridInventory = value; 
      RaisePropertyChanged("GridInventory");
    }
}

Upvotes: 2

Related Questions