0
A
回答
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>
相关问题
- 1. 在字符串匹配之前和之后的Python插入行
- 2. 在节点之前和之后插入
- 3. MySQL在查询中获取当前行之前和之后的行
- 4. 在JQuery中的选定行之后插入一个新行
- 5. 在大熊猫的兴趣行之前和之后选择行
- 6. 在第一行之前插入行
- 7. 如何在Android sqlite中的现有行之前插入新行?
- 8. 在javascript中选定的文本之前和之后插入文本
- 9. 以某种顺序选择“之前”给定行之前的行
- 10. 之前和之后的Git行号
- 11. 多行之前和之后的Mysql
- 12. MongoDB:在给定行之前和之后依次返回行?
- 13. 如何在模式之前和行号之后使用sed插入一行?
- 14. 获取具有特定条件的选定行的行之前和之后
- 15. 在删除wpf中的datagrid行之前删除确认C#
- 16. ie7在表单标签之后/之前插入换行符
- 17. SQL:给定行之前和之后的行
- 18. 在使用jQuery的当前行之后添加新表格行
- 19. 如何在当前行之后加入上面的行?
- 20. 正则表达式在字符之后插入点(。),在新行之前
- 21. 如何获取MYSQL中当前行之前的行的总和?
- 22. 使用:之前和之后:CSS选择器插入Html
- 23. 在使用sed的特定行之前插入多行文本
- 24. 在插入或更新之前检查MySQL行中的数据
- 25. SQL - 在列值更改之前和之后选择行日期
- 26. 如何将当前行移动到Vim之上的行之后?
- 27. Flatiron Union“之后”功能在“之前”功能之前执行?
- 28. NHibernate - 刷新之前/之后选择?
- 29. NSMutablearray在其他元素之前或之后插入新元素
- 30. 用途:之前和之后:页脚定位选择器之后
如果将的ItemSource绑定到一个ObservableCollection然后修改集合会做的伎俩。 你能分享你试过的代码吗? –
我试着玩数据网格的ControlTemplate,但没有成功。 –