2010-02-27 93 views

回答

2

如果數據綁定到網格集合實現INotifyCollectionChanged,加入新的項目到集合將行添加到數據網格。

當您從數據庫讀取數據時,將其存儲在ObservableCollection(實現此接口)中,然後將數據綁定到網格。

例子:

public class ViewModel { 

    public ObservableCollection<Data> Items { get; set; } 

    ... 

} 

在View.xaml:

... 
<DataGrid ItemsSource={Binding Path=Items}" ... /> 
... 

而且你要視圖的DataContext屬性設置爲視圖模型的實例。

從現在起,添加/刪除可觀察集合中的項目將自動觸發數據網格上的相同操作。

0

XAML:

<Window x:Class="NewItemEvent.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1" Height="341" Width="567" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"> 
<Grid> 
<my:DataGrid AutoGenerateColumns="False" Margin="0,0,0,29" Name="dataGrid1"> 
    <my:DataGrid.Columns> 
    <my:DataGridTemplateColumn Header="Name" Width="150"> 
     <my:DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
      <TextBlock Text="{Binding FirstName}" Margin="3 3 3 3"/> 
      <TextBlock Text="{Binding LastName}" Margin="3 3 3 3"/> 
      </StackPanel> 
     </DataTemplate> 
     </my:DataGridTemplateColumn.CellTemplate> 
     <my:DataGridTemplateColumn.CellEditingTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
      <TextBox Text="{Binding FirstName}" Margin="3 3 3 3"/> 
      <TextBox Text="{Binding LastName}" Margin="3 3 3 3"/> 
      </StackPanel> 
     </DataTemplate> 
     </my:DataGridTemplateColumn.CellEditingTemplate> 
    </my:DataGridTemplateColumn> 
    <my:DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="100"/> 
    </my:DataGrid.Columns> 
</my:DataGrid> 
<Button Height="23" HorizontalAlignment="Left" Name="AddNewRow" Click="AddNewRow_Click" VerticalAlignment="Bottom" Width="75">New Row</Button> 

代碼:

/// <summary> 
/// Interaction logic for Window1.xaml 
/// </summary> 
public partial class Window1 : Window 
{ 
    ObservableCollection<Person> People = new ObservableCollection<Person>(); 
    public Window1() 
    { 
     InitializeComponent(); 
     dataGrid1.ItemsSource = People; 
    } 

    private void AddNewRow_Click(object sender, RoutedEventArgs e) 
    { 
     People.Add(new Person() { FirstName = "Tom", LastName = "Smith", Age = 20 }); 
    } 
} 

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int Age { get; set; } 
} 
+0

感謝博·佩爾鬆編輯我的代碼。由於我是堆棧溢出的新手,因此難以理解流程。 – 2013-03-12 15:39:15

相關問題