2012-04-02 75 views
0

任何行,我有的数据网格这样的:的Datagrid绑定到数据表不显示动态添加到数据表

公共类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没有。 我在做什么错?

谢谢!

+0

它不会自动加载.....您需要通知已更改的集合....使用ObservableCollection ()用于修改集合更改.. – Ankesh 2012-04-02 08:26:31

+0

任何代码示例?不太清楚你的意思/从哪里开始。谢谢! – Anya 2012-04-02 08:36:20

回答

2

使用MVVM将是一个更好的apporach ....你甚至不会NEDD继承电网为了这个目的...

视图模型

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(); 
    } 
} 

现在添加NE的事情MyColleciton,它会自动在视图中reflectied .....

读了一些文章来回回MVVM实行更好地了解...

0

生成表的公共属性:

private DataTable m_Table 

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

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

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