我正在使用 WPF 数据网格。我需要在当前选定的行之前和之后插入新行。我怎样才能做到这一点?
有没有直接的方法?
我假设您有一个网格绑定到类似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>