2013-01-25 93 views
0

我正在使用WPF數據網格。我需要在當前選中的行之前和之後插入新行。我怎樣才能做到這一點?在wpf datagrid中當前選定的行之前和之後插入新行

有沒有直路?

+0

如果將的ItemSource綁定到一個ObservableCollection然後修改集合會做的伎倆。 你能分享你試過的代碼嗎? –

+0

我試着玩數據網格的ControlTemplate,但沒有成功。 –

回答

1

我假設你有一個網格綁定到類似ObservableCollection與SelectedItem屬性,如下所示: <DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">

所以,在您的視圖模型或代碼隱藏,你可以這樣做:

int currentItemPosition = Items.IndexOf(SelectedItem) + 1; 
if (currentItemPosition == 1) 
    Items.Insert(0, new Item { Name = "New Item Before" }); 
else 
    Items.Insert(currentItemPosition - 1, new Item { Name = "New Item Before" }); 

Items.Insert(currentItemPosition + 1, new Item { Name = "New Item After" }); 

這裏有一個完整的例子,我只是用一個空白WPF項目。 後面的代碼:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      Items = new ObservableCollection<Item> 
      { 
       new Item {Name = "Item 1"}, 
       new Item {Name = "Item 2"}, 
       new Item {Name = "Item 3"} 
      }; 

      DataContext = this; 
     } 

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

     public Item SelectedItem { get; set; } 

     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      int currentItemPosition = Items.IndexOf(SelectedItem) + 1; 
      if (currentItemPosition == 1) 
       Items.Insert(0, new Item { Name = "New Item Before" }); 
      else 
       Items.Insert(currentItemPosition - 1, new Item { Name = "New Item Before" }); 

      Items.Insert(currentItemPosition + 1, new Item { Name = "New Item After" }); 
     } 
    } 

    public class Item 
    { 
     public string Name { get; set; } 
    } 

XAML:

<Window x:Class="DataGridTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="*"/> 
     </Grid.RowDefinitions> 
     <Button Grid.Row="0" Content="Add Rows" Click="Button_Click_1" /> 
     <DataGrid Grid.Row="1" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" /> 
    </Grid> 
</Window> 
相關問題