首页 > 解决方案 > 将列表的内容数据绑定到数据网格

问题描述

我最近制作了一个由预先存在的表中的行组成的列表,并想尝试将该列表数据绑定到数据网格。然而,它只显示已定义的列名。有谁知道为什么这个绑定不起作用?

    public class ViewModel1 : ViewModelBase, INotifyPropertyChanged
    {

    public List<Table1> AllDatainTable { get; set; }

    private void SetInitialSettings()
    {
        AllDatainTable = new List<Table1>();
    }
    public List<Table1> GetAllDatainTable()
    {
        List<Table1> ret = new List<Table1>();
        Table entity;
        SqlDataAdapter da;
        DataTable dt = new DataTable();
        da = new SqlDataAdapter("SELECT * FROM Testdatabase.dbo.Table1", "Data Source=.;Initial Catalog=TestDatabase;Integrated Security=true");         
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            entity = new Testdatarow();
            entity.ID = Convert.ToInt32(dr["ID"]);
            entity.Name = dr["Name"].ToString();
            ret.Add(entity);
        }
        return ret;
    }

和 xaml

<DataGrid Grid.Row="1" Grid.RowSpan="6" x:Name="ContDatagrid" CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding AllDatainTable, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
             <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="SizeToHeader" />
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="SizeToHeader"/>
             </DataGrid.Columns> 
        </DataGrid>

以及数据模型本身

public class Table1 : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set
        {
            _ID = value;
            RaisePropertyChanged("ID");
        }
    }

    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            RaisePropertyChanged("Name");
        }
    }

    private void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

最后是它在一些早期测试中使用的连接字符串

  <connectionStrings>
      <add name="ConnectionToDb" connectionString="Data Source=.;Initial Catalog=Testdatabase;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>

标签: c#sqlwpfvisual-studioentity-framework

解决方案


您错误地声明了属性集合的类型。必须有一个可观察的集合(具有 INotifyCollectionChanged 实现)或一个 BindingList。

public class ViewModel1 : ViewModelBase, INotifyPropertyChanged
{

    public ObservableCollection<Table1> AllDatainTable { get; }
        = new ObservableCollection<Table1>();

    public ViewModel1() => Update();

    public void Update()
    {
        AllDatainTable.Clear();
        foreach (var item in GetAllDatainTable)
            AllDatainTable.Add(item);
    }
    public IReadOnlyList<Table1> GetAllDatainTable()
    {
        List<Table1> ret = new List<Table1>();
        Table entity;
        SqlDataAdapter da;
        DataTable dt = new DataTable();
        da = new SqlDataAdapter("SELECT * FROM Testdatabase.dbo.Table1", "Data Source=.;Initial Catalog=TestDatabase;Integrated Security=true");
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            entity = new Testdatarow();
            entity.ID = Convert.ToInt32(dr["ID"]);
            entity.Name = dr["Name"].ToString();
            ret.Add(entity);
        }
        return ret.AsReadOnly();
    }
}

而且从您的代码中不清楚如何将此 ViewModel 设置为 Window 的 DataContext,以及如何调用数据更新方法。
因此,错误可能不仅出现在您显示的代码中。


推荐阅读