[英]Datagrid that is bound to DataTable does not display any rows that are added dynamically to DataTable
我有這樣的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沒有。 我究竟做錯了什么?
謝謝!
使用MVVM將是一個更好的apporach ....你甚至不會為此目的繼承網格...
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");
}
}
}
<DataGrid ItemsSource={Binding Path=MyCollection}>
<!--Make Columns according to you-->
</DataGrid>
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
}
現在添加MyColleciton
到MyColleciton
,它將在View中自動反映.....
閱讀MVVm實現的一些文章,以便更好地理解......
使表成為公共財產:
private DataTable m_Table
public DataTable Table
{
get { return this.m_Table; }
protected set { m_Table = value; NotifyPropertyChanged("Table"); }
}
你還需要調用NotifyPropertyChanged(“Table”); 在你的AddRow函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.