【问题标题】:WPF Binding a List to a DataGridWPF 将列表绑定到 DataGrid
【发布时间】:2012-06-14 23:21:54
【问题描述】:

这是我第一次使用 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>

【问题讨论】:

    标签: c# wpf binding datagrid


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,datagrid 正在完美更新。
    【解决方案2】:

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

    InitializeComponent();
    
    DataContext = new ShellViewModel();
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        您可能需要考虑使用绑定 ObservableCollection 到数据网格。那么你就不需要维护一个私有成员_gridInventory和一个公共属性GridInventory

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

        【讨论】:

          猜你喜欢
          • 2010-12-16
          • 1970-01-01
          • 2021-03-18
          • 1970-01-01
          • 2021-08-26
          • 2021-04-11
          • 1970-01-01
          • 2011-04-13
          • 1970-01-01
          相关资源
          最近更新 更多