【问题标题】:Datagrid that is bound to DataTable does not display any rows that are added dynamically to DataTable绑定到 DataTable 的 Datagrid 不显示任何动态添加到 DataTable 的行
【发布时间】:2012-04-15 21:48:19
【问题描述】:

我有这样的数据网格:

公共类 myGrid : DataGrid {

    DataTable Table = new DataTable();

    public myGrid()
    {
    }

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        List<string> List = new List<string> { "Size1", "Size2", "Price", "Price2", "Note"} ;
        foreach (string Name in List)
        {
            Table.Columns.Add(Name);

            DataGridTextColumn c = new DataGridTextColumn();
            c.Header = Name;
            c.Binding = new Binding(Table.Columns[Name].ColumnName);
            this.Columns.Add(c);
        }

        DataColumn[] keys = new DataColumn[1];
        keys[0] = Table.Columns["PRICE"];
        Table.PrimaryKey = keys;

        this.DataContext = Table;
    }



    public void AddRow(object[] Values)
    {
            Table.LoadDataRow(Values, true);

    }

}

调用 AddRow 后,Table 确实有一行,但 myGrid 没有。 我做错了什么?

谢谢!

【问题讨论】:

  • 它永远不会自动加载.....您需要通知已更改的集合....使用 ObservableCollection () 通知集合更改..
  • 任何代码示例?不太清楚你的意思/从哪里开始。谢谢!

标签: c# wpf data-binding datagrid datatable


【解决方案1】:

将 Table 设为公共属性:

private DataTable m_Table

public DataTable Table
{
    get { return this.m_Table; }

    protected set { m_Table = value; NotifyPropertyChanged("Table"); }
}

您还需要调用 NotifyPropertyChanged("Table");在您的 AddRow 函数中。

【讨论】:

    【解决方案2】:

    使用 MVVM 将是一个更好的方法......您甚至不需要为此目的继承网格......

    查看模型

    class MyViewModel:INotifyPropertyChanged
    {
         private ObservableColleciton<string> myCollection;
    
       public MyViewModel()
       {
          //FunctiontoFillCollection()
       }
    
       public ObservableColleciton<string> MyCollection
       {
             get { return myCollection;}
             set
             {
                 mycolletion = value;
                 // i am leaving implemenation of INotifyPropertyChanged on you 
                 // google it.. :)
                 OnpropertyChanged("MyCollection");
             }
       }
    }
    

    View.Xaml

    <DataGrid ItemsSource={Binding Path=MyCollection}>
     <!--Make Columns according to you-->
    </DataGrid>
    

    View.xaml.cs

    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>
    public partial class MainView : Window
    {
        public MainView()
        {
            InitializeComponent();
            this.DataContext = new MyViewModel();
        }
    }
    

    现在给MyColleciton添加一个东西,它会自动反映在视图中.....

    阅读 MVVm implementation 的一些文章以更好地理解...

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 2012-11-22
      • 2011-10-12
      • 2014-01-13
      • 1970-01-01
      相关资源
      最近更新 更多