Silverlight4给DataGrid添加ContextMenu右键菜单

Toolkit Samples中的示例是将ContextMenu添加到ListBox的ItemTemplate中

而DataGrid由于没有ItemTemplate,所以稍有不同

XAML代码
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable
="d"
d:DesignHeight
="300" d:DesignWidth="400"
x:Class
="SilverlightApplication8.MainPage"
xmlns:data
="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data">

<Grid x:Name="LayoutRoot" Background="White">
<data:DataGrid Name="dg" ItemsSource="{Binding}" LoadingRow="dg_LoadingRow"/>
</Grid>
</UserControl>

添加引用System.Windows.Controls和System.Windows.Controls.Input.Toolkit

C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Windows.Data;
namespace SilverlightApplication8
{
public partial class MainPage : UserControl
{
PagedCollectionView pcv;

public MainPage()
{
InitializeComponent();

List
<Person> list = new List<Person>();
list.Add(
new Person { ID = 1, Name = "张三" });
list.Add(
new Person { ID = 2, Name = "李四" });
list.Add(
new Person { ID = 3, Name = "王五" });

pcv
= new PagedCollectionView(list);
dg.ItemsSource
= pcv;
}

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Person p
= ((MenuItem)sender).DataContext as Person;
if (p != null)
{
pcv.Remove(p);
}
}

private void dg_LoadingRow(object sender, DataGridRowEventArgs e)
{
DataGridRow dgr
= e.Row;
Person p
= (Person)dgr.DataContext;

ContextMenu cm
= new ContextMenu();
MenuItem mi
= new MenuItem();
mi.Header
= "删除 " + p.Name;
mi.Click
+= MenuItem_Click;
cm.Items.Add(mi);

ContextMenuService.SetContextMenu(dgr, cm);
}
}

public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
}

最好不要偷懒将ContextMenu直接作为DataGrid的右键菜单

这样在点击时需要根据DataGrid的SelectedItem获取选中行

就会造成当前选中第一行,鼠标放在第三行上右击"删除",最后却会删除第一行的情况

原文地址:https://www.cnblogs.com/zhlei616/p/1735625.html