• 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获取选中行

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

  • 相关阅读:
    Java经典面试题及详解
    linux nc命令使用详解
    终端下更改文件显示颜色
    第二章 IoC Setter注入
    网络抓包wireshark
    一些软件软件开发原则
    开发原则之约定大于配置
    2016第31周六
    2016第31周五
    2016年第31周四
  • 原文地址:https://www.cnblogs.com/zhlei616/p/1735625.html
Copyright © 2020-2023  润新知