2013-01-25 66 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> 
相关问题