很簡單,一個TextBlock而已 再搞出一個實體類 public class Person { public string FullName { get; set; } public int? Age { get; set; } public string Gender { get; set; } }
接著定義一個私有變數_personList並在初始化時為其添加幾項以便測試。 注:_personList是ObservableCollection,以下我們所有的操作都基於ObservableCollection。ObservableCollection<Person> _personList; _personList = new ObservableCollection<Person> { new Person(){ FullName="forever",Age=13,Gender="男" }, new Person(){ FullName="fish",Age=14,Gender="公"}, new Person(){ FullName="SBPP",Age=40,Gender="男"}, new Person(){FullName="TNT",Age=null,Gender="男"}, new Person(){FullName="SARS",Age=5,Gender="無"}, };
為了讓每一行的第一列產生自動編號,我們需要捕獲dataGrid1的LoadingRow事件,如dataGrid1.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid1_LoadingRow); void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e) { int index = e.Row.GetIndex(); var cell = dataGrid1.Columns.GetCellContent(e.Row) as TextBlock; cell.Text = (index + 1).ToString();} F5運行後點擊增加按鈕,你會發現數據源中新增的數據已經加入到DataGrid的新行中,並且第一列自動顯示了該行的行號。 現在我們開始解決第二個問題,即從數據源刪除數據時自動更新所有行號 現在GridView中再自定義一列,每列的顯示一個按鈕用來刪除該條數據<data:DataGridTemplateColumn> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="刪除" Click="btnDel_Click" /> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate></data:DataGridTemplateColumn>
然後在.cs中處理btnDel_Click事件private void btnDel_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; var index = _personList.IndexOf(btn.DataContext as Person); _personList.RemoveAt(index); foreach (var item in dataGrid1.ItemsSource) { var txtBlock = dataGrid1.Columns.GetCellContent(item) as TextBlock; txtBlock.Text = (DataGridRow.GetRowContainingElement(txtBlock).GetIndex() + 1).ToString(); }} ok,大功告成。 如果您有更好的方法,請告訴我,多謝。