2012-06-14 159 views
0

這是我第一次使用WPF數據網格。根據我的理解,我應該在我的視圖模型中將網格綁定到公共物件。下面是ViewModel代碼,當我逐步調試器GridInventory被設置爲包含2606記錄的列表時,但是這些記錄從不顯示在數據網格中。我究竟做錯了什麼?WPF將列表綁定到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> 

回答

2

我認爲你需要在你的GridInventory二傳手呼籲raisepropertychanged事件,以便視圖可以得到通知。

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

謝謝,datagrid現在正在更新完美。 – bzsparks

0

頁的DataContext的未綁定到視圖模型的實例。在InitializeComponent調用後,後面的代碼,分配的datacontext如:

InitializeComponent(); 

DataContext = new ShellViewModel(); 
0

我想你應該在視圖模型和模型中使用RaisePropertyChanged,也應該設置的DataContext在視圖中。

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

您可能想考慮使用bind ObservableCollection綁定到數據網格。那麼你不需要維護一個私人成員_gridInventory和一個公共屬性GridInventory

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