C# WPF将列表绑定到数据网格
这是我第一次使用WPF数据网格。据我所知,我应该将网格绑定到viewmodel中的公共属性。下面是ViewModel代码,当我逐步通过调试器GridInventory时,它被设置为包含2606条记录的列表,但是这些记录从未显示在datagrid中。我做错了什么C# WPF将列表绑定到数据网格,c#,wpf,binding,datagrid,C#,Wpf,Binding,Datagrid,这是我第一次使用WPF数据网格。据我所知,我应该将网格绑定到viewmodel中的公共属性。下面是ViewModel代码,当我逐步通过调试器GridInventory时,它被设置为包含2606条记录的列表,但是这些记录从未显示在datagrid中。我做错了什么 public class ShellViewModel : PropertyChangedBase, IShell { private List<ComputerRecord> _gridInventory;
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();
}
}
}
公共类ShellViewModel:PropertyChangedBase,IShell
{
私人清单(清单);;
公开清单清单
{
获取{return\u gridInventory;}
设置{u gridInventory=value;}
}
公共作废选择()
{
var builder=新的SqlConnectionBuilder();
使用(var db=newdatacontext(builder.GetConnectionObject(\u serverName,\u dbName)))
{
var record=db.GetTable().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>
我认为您需要在GridInventory setter中调用raisepropertychanged事件,以便视图能够得到通知
public List<ComputerRecord> GridInventory
{
get { return _gridInventory; }
set
{ _gridInventory = value;
RaisePropertyChanged("GridInventory");
}
}
公共列表目录
{
获取{return\u gridInventory;}
设置
{{u=价值;
RaisePropertyChanged(“网格库存”);
}
}
页面的datacontext未绑定到视图模型的实例。在InitializeComponent调用后的代码中,分配datacontext,例如:
InitializeComponent();
DataContext = new ShellViewModel();
我认为应该在ViewModel和Model中使用RaisePropertyChanged,还应该在视图中设置DataContext
<Window.DataContext>
<local:ShellViewModel />
</Window.DataContext>
< /代码> 您可能想考虑将绑定SeababelCelk收集到DATAGRID中。然后,您不需要维护私有成员\u gridInventory和公共属性gridInventory
//viewModel.cs
public ObservableCollection<ComputerRecord> GridInventory {get; private set;}
//view.xaml
<DataGrid ... ItemsSource="{Binding GridInventory}" .../>
//viewModel.cs
公共ObservableCollection GridInventory{get;private set;}
//view.xaml
谢谢,datagrid现在正在完美更新。