Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using Microsoft.Practices.Prism.Commands;
- namespace Client.Models
- {
- /// <summary>
- /// Provides global DatgGrid context menu functions
- /// </summary>
- public class DataGridContextMenus
- {
- static readonly DataGridContextMenus _instance = new DataGridContextMenus();
- public static DataGridContextMenus Instance
- {
- get { return _instance; }
- }
- /// <summary>Called by the price grid's context menu</summary>
- public ICommand ExportGridToExcelCommand { get; set; }
- /// <summary>Called by the grid's context menu</summary>
- public ICommand CopyGridToClipboardCommand { get; set; }
- public DataGridContextMenus()
- {
- ExportGridToExcelCommand = new DelegateCommand<object>(OnExportGridToExcel);
- CopyGridToClipboardCommand = new DelegateCommand<object>(OnCopyToClipboard);
- }
- void OnExportGridToExcel(object sender)
- {
- var cm = sender as ContextMenu;
- if (cm == null)
- return;
- var grid = cm.PlacementTarget as DataGrid;
- if (grid == null)
- return;
- var result = CopyGridToClipboard(grid);
- string tempfile = Path.Combine(Path.GetTempPath(), string.Format("Exported_{0}.csv", DateTime.Now.Ticks));
- using (StreamWriter sw = new StreamWriter(tempfile))
- {
- sw.Write(result);
- sw.Close();
- Process.Start(new ProcessStartInfo(tempfile) { UseShellExecute = true });
- }
- }
- void OnCopyToClipboard(object sender)
- {
- var cm = sender as ContextMenu;
- if (cm == null)
- return;
- var grid = cm.PlacementTarget as DataGrid;
- if (grid == null)
- return;
- CopyGridToClipboard(grid);
- }
- string CopyGridToClipboard(DataGrid grid)
- {
- DataGridSelectionMode selectionMode = grid.SelectionMode;
- try
- {
- if (selectionMode != DataGridSelectionMode.Extended)
- grid.SelectionMode = DataGridSelectionMode.Extended;
- grid.SelectAllCells();
- grid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
- ApplicationCommands.Copy.Execute(null, grid);
- }
- finally
- {
- grid.UnselectAllCells();
- if (selectionMode != DataGridSelectionMode.Extended)
- grid.SelectionMode = selectionMode;
- }
- string result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment