绑定到DataTable的Datagrid不会显示动态添加到DataTable的任何行

时间:2012-04-02 08:16:47

标签: c# wpf data-binding datagrid datatable

我有像这样的dataGrid:

public class 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没有。 我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分: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实现的一些文章以便更好地理解......

答案 1 :(得分:0)

将表格设为公共财产:

private DataTable m_Table

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

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

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