LoginSignup
0
1

More than 1 year has passed since last update.

WPF コードビハインドでDataGridのデータをクリップボードにコピー

Last updated at Posted at 2022-12-09

もっとスマートな方法がありそうな気もしますが。
意外と苦労したので備忘録として残しておきます。
DataGrid.Rowsプロパティとか用意されていないんですかね。

BindingするItemはインデクサを設定する必要があります。

#region インデクサ
/// <summary>
/// インデクサでアクセスするプロパティ
/// </summary>
/// <param name="propertyName">プロパティ名</param>
/// <returns>Object</returns>
public object this[string propertyName]
{
    get
    {
       return typeof(hogeClass).GetProperty(propertyName).GetValue(this);
    }

    set
    {
       typeof(hogeClass).GetProperty(propertyName).SetValue(this, value);
    }
 }
#endregion
public static void DataGridCopyToClipboard(DataGrid dataGrid)
{
    if (dataGrid == null) return;
    StringBuilder sb = new();
    string s = "";
    List<String> bindingItems = new List<string>();
    // ヘッダタイトルを出力
    foreach (DataGridColumn column in dataGrid.Columns)
    {
        if (column is DataGridBoundColumn && column.Visibility == Visibility.Visible)
        {
            s += column.Header.ToString() + "\t";
            DataGridBoundColumn boundColumn = (DataGridBoundColumn)column;
            Binding binding = (Binding)boundColumn.Binding;
            var path = binding.Path.Path;
            bindingItems.Add(path);
        }
    }
    sb.AppendLine(s.Trim('\t'));
    s = "";
    foreach (var row in dataGrid.Items)
    {
        // hogeClassはクラスです
        if (row is hogeClass)
        {
            hogeClass hogehoge = (hogeClass)row;
            foreach (string itemName in bindingItems)
            {
                s += hogehoge[itemName]?.ToString() + "\t";
            }
            sb.AppendLine(s.Trim('\t'));
            s = "";
        }
    }
    try
    {
        Clipboard.Clear();
        Clipboard.SetDataObject(sb.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1