【问题标题】:MahApps DataGrid unable to take user input and write to csvMahApps DataGrid 无法接受用户输入并写入 csv
【发布时间】:2015-07-14 22:04:55
【问题描述】:

任何帮助将不胜感激。对不起,如果我的代码是初级的。我是 C# 新手。

问题

我使用 MahAppsflyout 中动态创建了多个DataGridsDataGridsCSV 文件 (ConvertCSVtoDataTable()) 填充。我希望用户能够对 DataGrids 进行更改,完成后,DataGrids 值将替换 CSV 文件(UpdateDataGridParameter())。

UI 树:Flyout > StackPanel > GroupBox > DataGrid

问题

DG.SelectAllCells() 不会从用户更改DataGrid 中选择。如何获取 DataGid 的 VISUAL UI 表示或将 DT 属性绑定到数据更改事件。我希望我正确地解释了这一点。如果您有任何问题可以帮助我,请发帖,我会尽快回复。谢谢

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace SpiderRoll.Classes
{
    public class DataGridProperties 
    {
        private int IDValue;
        public int ID
        {
            get { return IDValue; }
            set { IDValue = value; }
        }

        private string HeaderValue;
        public string Header
        {
            get { return HeaderValue; }
            set { HeaderValue = value; }
        }

        private string DescriptionValue;
        public string Description
        {
            get { return DescriptionValue; }
            set { DescriptionValue = value; }
        }

        private string NameValue;
        public string Name
        {
            get { return NameValue; }
            set { NameValue = value; }
        }

        private string FilePathValue;
        public string FilePath
        {
            get { return FilePathValue; }
            set { FilePathValue = value; }
        }

        private DataTable DTValue;
        public DataTable DT
        {
            get
            {
                return DTValue;
            }
            set
            {
                DTValue = value;
            }
        }

        public static DataGridProperties DataGridObject(List<DataGridProperties> TBP, int ID = 0, string Name = "")
        {
            foreach (var tb in TBP)
            {
                if (tb.ID == ID || tb.Name == Name)
                {
                    return tb;
                }
            }
            return null;
        }

        public static int FindDataGridID(List<DataGridProperties> DGP, string Name = "")
        {
            int i = 0;
            foreach (var dg in DGP)
            {
                if (dg.Name == Name)
                {
                    return i;
                }
                i++;
            }
            return -1;
        }

        public static GroupBox DataGridPropertieStackPanel(DataGridProperties DataGrid)  // DataGridProperties DataGrid
        {
            GroupBox GB = new GroupBox();
            GB.Header = DataGrid.Header;

            StackPanel SPMain = new StackPanel();
            SPMain.Orientation = System.Windows.Controls.Orientation.Vertical;

            System.Windows.Controls.Label LBDescription = new System.Windows.Controls.Label();
            LBDescription.Content = DataGrid.Description;
            LBDescription.Margin = new Thickness(10, 0, 0, 0);
            SPMain.Children.Add(LBDescription);

            StackPanel SP = new StackPanel();
            SP.Name = DataGrid.Name;
            SP.Orientation = System.Windows.Controls.Orientation.Horizontal;
            SP.Margin = new Thickness(10);

            System.Windows.Controls.DataGrid DG = new System.Windows.Controls.DataGrid();
            DG.Name = DataGrid.Name;
            DG.CanUserAddRows = false;
            DG.ItemsSource = DataGrid.DT.DefaultView;


            SP.Children.Add(DG);
            SPMain.Children.Add(SP);
            GB.Content = SPMain;
            return GB;
        }

        public static DataTable ConvertCSVtoDataTable(string FilePath)
        {
            StreamReader sr = new StreamReader(FilePath);
            string[] headers = sr.ReadLine().Split(',');
            string[] firstLine = sr.ReadLine().Split(',');
            DataTable dt = new DataTable();
            DataColumn column = new DataColumn();
            DataRow fl = dt.NewRow();
            int idx = 0;

            foreach (string header in headers)
            {
                //If bool is in first row, turn the column into a checkbox.
                if (firstLine[idx].ToLower() == "true" || firstLine[idx].ToLower() == "false")
                {
                    column = dt.Columns.Add(header, typeof(bool));
                }
                else
                {
                    column = dt.Columns.Add(header, typeof(string));
                    column.ReadOnly = true;
                }
                if (header.EndsWith("~"))
                {
                    column.ReadOnly = true;
                }
                //Reading and building the first row
                fl[idx] = firstLine[idx];
                idx++;
            }
            //Adding first row
            dt.Rows.Add(fl);

            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                string[] rows = line.Split(',');
                DataRow dr = dt.NewRow();
                for (int i = 0; i < headers.Length; i++)
                {
                    dr[i] = rows[i];
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public static void UpdateDataGridParameter(DataGrid DG)
        {
            StringBuilder sb = new StringBuilder();
            IEnumerable<string> columnNames = DG.Columns.Cast<DataGridColumn>().
                                              Select(column => column.Header.ToString());

            sb.AppendLine(string.Join(",", columnNames));

            DG.UnselectAllCells();
            DG.SelectAllCells();
            foreach (DataRowView row in DG.SelectedItems)
            {
                IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
                sb.AppendLine(string.Join(",", fields));
            }
            DG.UnselectAllCells();
            var filePath = @"C:\IO\" + DG.Name + ".csv";
            File.WriteAllText(filePath, sb.ToString());
        }
    }
}

在 Class Bundle 中,我创建了一个 DataGrids 列表

    private List<DataGridProperties> dataGridList;
    public List<DataGridProperties> DataGridList
    {
        get
        {
            return dataGridList;
        }
        set
        {
            dataGridList = value;
        }
    }

Main 中,我通过调用DataGridPropertieStackPanel 函数迭代DataGridlist 并填充StackPanels

                        foreach (var item in bundle.DataGridList)
                        {
                            if (item.Name == DataGrid.Name)
                            {
                                sPanelParameters.Children.Add(DataGridProperties.DataGridPropertieStackPanel(item));
                            }
                        }

【问题讨论】:

  • 使用“ObservableCollection”而不是“列表”。并参考link 使用双向绑定。
  • 谢谢,Akansha 我会考虑这个作为解决方案。

标签: c# wpf csv datagrid mahapps.metro


【解决方案1】:

更改值后,您的 DataGrid 会更新绑定的 DataView。您不必选择和取消选择网格行,只需直接访问数据视图。您的代码版本略有更改:

public static void UpdateDataGridParameter(DataGrid dataGrid)
{
    StringBuilder sb = new StringBuilder();
    var dataView = dataGrid.ItemsSource as DataView;
    var columnNames = dataView.Table.Columns
            .Cast<DataColumn>()
            .Select(column => column.ColumnName);

    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRowView row in dataView)
    {
        IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
        sb.AppendLine(string.Join(",", fields));
    }

    var filePath = @"C:\IO\" + dataGrid.Name + ".csv";
    File.WriteAllText(filePath, sb.ToString());
}

【讨论】:

  • Gosha - dataView 数据集仍显示未修改的数据网格值。我假设“DG.ItemsSource = DataGrid.DT.DefaultView;”是问题所在。感谢您的意见。
猜你喜欢
  • 1970-01-01
  • 2013-05-02
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2020-11-13
  • 2012-07-18
相关资源
最近更新 更多