在wpf datagrid中的当前所选行之前和之后插入一个新行

时间:2013-01-25 05:51:00

标签: wpf xaml datagrid row

我正在使用WPF数据网格。我需要在当前选定的行之前和之后插入新行。我怎么能这样做?

有直道吗?

1 个答案:

答案 0 :(得分: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>