簡體   English   中英

WPF將列表綁定到DataGrid

[英]WPF Binding a List to a 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>

我認為您需要在GridInventory setter中調用raisepropertychanged事件,以便可以通知視圖。

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

頁面的datacontext未綁定到View Model的實例。 在InitializeComponent調用之后的代碼中,分配datacontext,例如:

InitializeComponent();

DataContext = new ShellViewModel();

我認為您應該在ViewModel和Model中使用RaisePropertyChanged,還應該在View中設置DataContext。

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

您可能需要考慮將bind ObservableCollection用於datagrid。 然后,您不需要維護私有成員_gridInventory和公共屬性GridInventory

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM