给DataGrid加上右键菜单

给DataGrid加上右键菜单

     

         SunHai

   开发工具:Microsoft Visual Studio .NET 2003
   操作系统:Windows XP

                 用XML作为DataGrid的数据源

  码如下:

Dim fileName As String
Dim MyXmlDataSet As New DataSet
fileName = "sunhai.xml"
MyXmlDataSet.ReadXml(fileName)
Form1.DefInstance.DataGrid1.DataSource = MyXmlDataSet


  启动程序,DataTable默认是闭合的,需要手动点击展开,不胜其烦,用如下代码实现自动展开DataTable:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

  DataGrid1.Expand(-1) '要展开的行数,设为-1表示展开所有行
  DataGrid1.NavigateTo(0, "DataTableName")

End Sub


   

  
                获得在DataGrid1鼠标右击的座标

Dim rowNum, columnNum As Integer '分别是行号和列号
Private Sub DataGrid1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGrid1.MouseDown

   Dim myGrid As DataGrid = CType(sender, DataGrid)
  Dim hti As System.Windows.Forms.DataGrid.HitTestInfo
  hti = myGrid.HitTest(e.X, e.Y)

  If e.Button = MouseButtons.Right And e.Clicks = 1 Then '如果是鼠标右击
     Select Case hti.Type '
       Case System.Windows.Forms.DataGrid.HitTestType.Cell,         System.Windows.Forms.DataGrid.HitTestType.RowHeader,         System.Windows.Forms.DataGrid.HitTestType.ColumnHeader

         rowNum = hti.Row     '获得鼠标右击所在行
         columnNum = hti.Column '获得鼠标右击所在列
     End Select

  End If

End Sub

                 

                  添加ContextMenu

  在设计模式添加ContextMenu1:
  Text      Name
  删除一行    mnuDeleteRow
  插入一行     mnuInsertRow

 把DataGrid1属性中的ContextMenu设为ContextMenu1。

Private Sub mnuDeleteRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDeleteRow.Click

  MyXmlDataSet.Tables(0).Rows.RemoveAt(rowNum) '删除行

End Sub

 

Private Sub mnuInsertRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuInsertRow.Click

  Dim row1 As DataRow = MyXmlDataSet.Tables(0).NewRow
  MyXmlDataSet.Tables(0).Rows.InsertAt(row1, rowNum)
  MyXmlDataSet.AcceptChanges()  '不加这句,你会发现所插入行都到“最后”了

End Sub


 
    怎么在DataTable中插入列呢?请各位指教!

                            2004年4月27日

我的QQ:  26624998
我的网站:
http://blog.youkuaiyun.com/2066/

这是我的代码,找找问题在哪Items.cs内容为// File: Item.cs using System.Collections.ObjectModel; using System.ComponentModel; namespace Zyan { public class Item : INotifyPropertyChanged { public int id { get; set; } = 1; private ObservableCollection<Row> _rows = new(); public ObservableCollection<Row> rows { get => _rows; set { _rows = value; OnPropertyChanged(nameof(rows)); UpdateStatistics(); // 数据重置时也更新统计 } } // 统计字段(只读) private int _totalCount; private int _pendingCount; private int _markedCount; private int _completedCount; private int _rejectedCount; private int _approvedCount; public int TotalCount { get => _totalCount; private set { _totalCount = value; OnPropertyChanged(nameof(TotalCount)); } } public int PendingCount { get => _pendingCount; private set { _pendingCount = value; OnPropertyChanged(nameof(PendingCount)); } } public int MarkedCount { get => _markedCount; private set { _markedCount = value; OnPropertyChanged(nameof(MarkedCount)); } } public int CompletedCount { get => _completedCount; private set { _completedCount = value; OnPropertyChanged(nameof(CompletedCount)); } } public int RejectedCount { get => _rejectedCount; private set { _rejectedCount = value; OnPropertyChanged(nameof(RejectedCount)); } } public int ApprovedCount { get => _approvedCount; private set { _approvedCount = value; OnPropertyChanged(nameof(ApprovedCount)); } } // 时间戳 private DateTime _lastEditedTime = DateTime.Now; public DateTime lastEditedTime { get => _lastEditedTime; private set { _lastEditedTime = value; OnPropertyChanged(nameof(lastEditedTime)); } } public Item() { // 初始化空集合 rows = new ObservableCollection<Row>(); UpdateStatistics(); } public void UpdateStatistics() { TotalCount = rows.Count; PendingCount = rows.Count(r => r.state == RowState.Pending); MarkedCount = rows.Count(r => r.state == RowState.Marked); CompletedCount = rows.Count(r => r.state == RowState.Completed); RejectedCount = rows.Count(r => r.state == RowState.Rejected); ApprovedCount = rows.Count(r => r.state == RowState.Approved); } public void UpdateLastEditedTime() { lastEditedTime = DateTime.Now; } public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } 后端 using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using System.Collections.ObjectModel; using System.IO; using System.ComponentModel; namespace Zyan { /// <summary> /// 主窗口 - 使用 Item 类管理文档与状态统计 /// </summary> public partial class MainWindow : Window { // 当前打开的项目 private Item? _currentItem; // 暴露给 XAML 绑定的属性 public Item? CurrentItem { get => _currentItem; set { _currentItem = value; OnPropertyChanged(nameof(CurrentItem)); } } // 定义命令 public static readonly RoutedCommand SetStateCommand = new RoutedCommand(); public MainWindow() { InitializeComponent(); // 设置 DataContext 为当前窗口本身(支持绑定 CurrentItem) DataContext = this; // 绑定命令处理 CommandBindings.Add(new CommandBinding(SetStateCommand, OnSetStateExecuted)); // 初始化 DataGrid 列(如果未在 XAML 中定义) SetupDataGridColumns(); } #region 命令处理 private void OnSetStateExecuted(object sender, ExecutedRoutedEventArgs e) { if (e.Parameter is RowState newState && dg_wp.SelectedItem is Row selectedRow && CurrentItem != null) { selectedRow.state = newState; CurrentItem.UpdateStatistics(); // 手动触发统计更新 CurrentItem.UpdateLastEditedTime(); // 更新时间戳 } } #endregion #region 文件操作 private void chooseFile(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*", DefaultExt = ".txt" }; if (openFileDialog.ShowDialog() == true) { LoadFile(openFileDialog.FileName); } } private void LoadFile(string filePath) { try { string[] lines = File.ReadAllLines(filePath, Encoding.UTF8); // 创建新的 Item 实例 var item = new Item { id = 1 }; // 可改进为基于路径生成唯一 ID item.rows.Clear(); for (int i = 0; i < lines.Length; i++) { item.rows.Add(new Row { id = i, original = lines[i], translation = string.Empty, state = RowState.Pending }); } // 提交为当前项目 CurrentItem = item; // 绑定DataGrid dg_wp.ItemsSource = CurrentItem.rows; // 显示提示 MessageBox.Show($"Loaded {item.TotalCount} lines.", "Success", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show($"Failed to load file: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } #endregion #region 辅助方法 private void SetupDataGridColumns() { // 如果你在 XAML 中已经定义了列,可以删除此部分 // 否则动态添加列(示例) } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler? PropertyChanged; #endregion // 其他事件留空... private void click_page(object sender, RoutedEventArgs e) { } } } 前端<Window x:Class="Zyan.MainWindow" 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" xmlns:local="clr-namespace:Zyan" mc:Ignorable="d" Title="Zyan" Height="550" Width="800"> <!-- ==================== Resources: Remove unused ObjectDataProvider ==================== --> <!-- 我们不再需要 ObjectDataProvider,直接使用 {x:Static} --> <Grid Background="#E5E5E5"> <!-- 3 rows --> <Grid.RowDefinitions> <!-- row.0 Tool Bar --> <RowDefinition Height="Auto"/> <!-- row.1 Data View --> <RowDefinition Height="*"/> <!-- row.2 Overview --> <RowDefinition Height="Auto" MinHeight="30"/> </Grid.RowDefinitions> <!-- ==================================== Tool Bar ==================================== --> <TabControl Name="tab_wp" TabStripPlacement="Top" FontSize="12" Grid.Row="0"> <TabItem Name="Project" Header="Project"> <DockPanel LastChildFill="False"> <Button Name="bt_open" Content="Open" Click="chooseFile"/> <Button Name="bt_save" Content="Save"/> <Button Name="bt_save_as" Content="Save As"/> </DockPanel> </TabItem> <TabItem Name="Lib" Header="Library"> <DockPanel LastChildFill="False"> <Button Name="bt_add_lib" Content="Add"/> </DockPanel> </TabItem> <TabItem Name="Online" Header="Online"/> <TabItem Name="Review" Header="Review"/> <TabItem Name="Settings" Header="Settings"/> </TabControl> <!-- ==================================== DataGrid ==================================== --> <DataGrid Name="dg_wp" Grid.Row="1" Background="White" FrozenColumnCount="1" AutoGenerateColumns="False" CanUserReorderColumns="False" CanUserSortColumns="False" CanUserAddRows="False" CanUserResizeColumns="False" ColumnWidth="*"> <!-- ==================== DataGridRow Style with ContextMenu & Triggers ==================== --> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <!-- 默认背景白色 --> <Setter Property="Background" Value="White"/> <!-- ==================== 右键菜单 ==================== --> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <!-- Pending: 透明背景 --> <MenuItem Header="Pending" Command="{x:Static local:MainWindow.SetStateCommand}" CommandParameter="{x:Static local:RowState.Pending}"> <MenuItem.Style> <Style TargetType="MenuItem"> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="FontSize" Value="12"/> </Style> </MenuItem.Style> </MenuItem> <!-- Marked: 浅黄 --> <MenuItem Header="Marked" Command="{x:Static local:MainWindow.SetStateCommand}" CommandParameter="{x:Static local:RowState.Marked}"> <MenuItem.Style> <Style TargetType="MenuItem"> <Setter Property="Background" Value="#FFF9E6"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="BorderBrush" Value="#FFE599"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="FontSize" Value="12"/> </Style> </MenuItem.Style> </MenuItem> <!-- Completed: 浅蓝 --> <MenuItem Header="Completed" Command="{x:Static local:MainWindow.SetStateCommand}" CommandParameter="{x:Static local:RowState.Completed}"> <MenuItem.Style> <Style TargetType="MenuItem"> <Setter Property="Background" Value="#E6F3FF"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="BorderBrush" Value="#99CFFF"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="FontSize" Value="12"/> </Style> </MenuItem.Style> </MenuItem> <!-- Rejected: 浅红 --> <MenuItem Header="Rejected" Command="{x:Static local:MainWindow.SetStateCommand}" CommandParameter="{x:Static local:RowState.Rejected}"> <MenuItem.Style> <Style TargetType="MenuItem"> <Setter Property="Background" Value="#FFE6E6"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="BorderBrush" Value="#FF9999"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="FontSize" Value="12"/> </Style> </MenuItem.Style> </MenuItem> <!-- Approved: 浅绿 --> <MenuItem Header="Approved" Command="{x:Static local:MainWindow.SetStateCommand}" CommandParameter="{x:Static local:RowState.Approved}"> <MenuItem.Style> <Style TargetType="MenuItem"> <Setter Property="Background" Value="#E6FFE6"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Padding" Value="10,5"/> <Setter Property="BorderBrush" Value="#99CC99"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="FontSize" Value="12"/> </Style> </MenuItem.Style> </MenuItem> </ContextMenu> </Setter.Value> </Setter> <!-- ==================== 根据 state 设置行背景色 ==================== --> <Style.Triggers> <DataTrigger Binding="{Binding state}" Value="{x:Static local:RowState.Pending}"> <Setter Property="Background" Value="Transparent"/> </DataTrigger> <DataTrigger Binding="{Binding state}" Value="{x:Static local:RowState.Marked}"> <Setter Property="Background" Value="#FFF9E6"/> </DataTrigger> <DataTrigger Binding="{Binding state}" Value="{x:Static local:RowState.Completed}"> <Setter Property="Background" Value="#E6F3FF"/> </DataTrigger> <DataTrigger Binding="{Binding state}" Value="{x:Static local:RowState.Rejected}"> <Setter Property="Background" Value="#FFE6E6"/> </DataTrigger> <DataTrigger Binding="{Binding state}" Value="{x:Static local:RowState.Approved}"> <Setter Property="Background" Value="#E6FFE6"/> </DataTrigger> </Style.Triggers> </Style> </DataGrid.RowStyle> <!-- ==================== Columns ==================== --> <DataGrid.Columns> <DataGridTextColumn Header="No." Width="Auto" Binding="{Binding id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True"/> <DataGridTextColumn Header="Original" Width="*" Binding="{Binding original, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True"/> <DataGridTextColumn Header="Translation" Width="*" Binding="{Binding translation, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> </DataGrid.Columns> </DataGrid> <!-- ==================================== Overview Panel ==================================== --> <Grid Name="Overview" Grid.Row="2"> <!-- 后续添加统计信息 --> <StackPanel Orientation="Horizontal" Height="Auto" Background="#FFFACD"> <TextBlock Text="{Binding CurrentItem.TotalCount, StringFormat='Total {0}'}" Margin="5"/> <TextBlock Text="{Binding CurrentItem.PendingCount, StringFormat='Pending {0}'}" Foreground="LightGray" Margin="5"/> <TextBlock Text="{Binding CurrentItem.MarkedCount, StringFormat='Marked {0}'}" Foreground="LightYellow" Margin="5"/> <TextBlock Text="{Binding CurrentItem.CompletedCount, StringFormat='Completed {0}'}" Foreground="LightBlue" Margin="5"/> <TextBlock Text="{Binding CurrentItem.RejectedCount, StringFormat='Rejected {0}'}" Foreground="Red" Margin="5"/> <TextBlock Text="{Binding CurrentItem.ApprovedCount, StringFormat='Approved {0}'}" Foreground="LightGreen" Margin="5"/> <TextBlock Text="{Binding CurrentItem.lastEditedTime, StringFormat='LastEditedTime {0}'}" Margin="5"/> </StackPanel> </Grid> </Grid> </Window>
最新发布
12-25
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值