WPF将列表绑定到DataGrid

时间:2012-06-14 23:21:55

标签: c# wpf binding datagrid

这是我第一次使用WPF数据网格。根据我的理解,我应该将网格绑定到我的viewmodel中的公共属性。下面是ViewModel代码,因为我逐步调试GridInventory被设置为包含2606条记录的List,但这些记录从未在datagrid中显示。我究竟做错了什么?

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();
        }
    }
}

我的XAML

<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>

4 个答案:

答案 0 :(得分:2)

我认为您需要在GridInventory setter中调用raisepropertychanged事件,以便可以通知视图。

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

答案 1 :(得分:0)

页面的datacontext未绑定到View Model的实例。在InitializeComponent调用之后的代码中,分配datacontext,例如:

InitializeComponent();

DataContext = new ShellViewModel();

答案 2 :(得分:0)

我认为您应该在ViewModel和Model中使用RaisePropertyChanged,并且还应该在View中设置DataContext。

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

答案 3 :(得分:0)

您可能需要考虑将bind ObservableCollection用于datagrid。那么你不需要维护一个私有成员_gridInventory和一个公共属性GridInventory

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