簡體   English   中英

單擊datagrid外部的按鈕時如何將新行添加到datagrid(WPF工具包)

[英]How to add a new row to a datagrid(WPF toolkit) when click on a button in the outside of datagrid

單擊數據網格外部的按鈕時,我想在數據網格中添加新行。 datagrid與SQL Server數據庫綁定,並且在運行時它具有一些數據,我想通過數據庫將新數據添加到數據庫中

我嘗試了很多,但是沒有成功

有人回復我對我會非常有幫助...

提前謝謝..

如果綁定到網格的數據集合實現INotifyCollectionChanged,則向集合添加新項會將行添加到datagrid。

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

例:

public class ViewModel {

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

   ...

}

在View.xaml中:

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

並且您必須將視圖的DataContext屬性設置為ViewModel的實例。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM