WPF 将列表绑定到数据网格

本文关键字:数据 数据网 网格 绑定 列表 WPF | 更新日期: 2023-09-27 18:37:20

这是我第一次使用 WPF 数据网格。 据我所知,我应该将网格绑定到我的观点模型中的公共属性。 下面是 ViewModel 代码,当我逐步执行调试器时,GridInventory 被设置为包含 2606 条记录的列表,但这些记录永远不会显示在数据网格中。 我做错了什么?

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>

WPF 将列表绑定到数据网格

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

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

页面的数据上下文未绑定到视图模型的实例。在 InitializeComponent 调用后的代码隐藏中,分配数据上下文,例如:

InitializeComponent();
DataContext = new ShellViewModel();

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

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

您可能需要考虑将 ObservableCollection 绑定到数据网格。然后,您不需要维护私有成员_gridInventory和公共属性 GridInventory

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