如何在wpf中将动态数据绑定到数据网格?

时间:2016-09-22 12:26:48

标签: c# wpf xaml data-binding

我将以下类作为我的DataModel:

public class InspectorOutput
{
    string m_SymbolName;
    // Each string is a column name with its value in double
    List<KeyValuePair<string, double>> m_ListPrices = new List<KeyValuePair<string, double>>();

    public string SymbolName
    {
        get
        {
            return m_SymbolName;
        }

        set
        {
            m_SymbolName = value;
        }
    }

    public List<KeyValuePair<string, double>> ListPrices
    {
        get
        {
            return m_ListPrices;
        }

        set
        {
            m_ListPrices = value;
        }
    }
    public void addResult(string strResultName, double nResult)
    {
        ListPrices.Add(new KeyValuePair<string, double>(strResultName, nResult));
    }
}

在我的xaml窗口中,数据网格定义如下:

<DataGrid x:Name="gridStockData">
                </DataGrid>

稍后,在我的主窗口中,我有以下代码:

    private void runProfile(object sender, RoutedEventArgs e)
    {
        ObservableCollection<InspectorOutput> listOutput = null;
        Profile.Profile objProfile = null;
        Inspector.InspectorManager objInspectorManager = null;
        try
        {
            // Some code here which makes a profile out of user input in objProfile
            objInspectorManager = new Inspector.InspectorManager();
            // Calculate data based on given profile
            listOutput = objInspectorManager.startInspector(objProfile);
            // Show calculated data
            gridStockData.ItemsSource = listOutput;
        }
        catch (Exception ex)
        {
            Logger.getInstance().error(ex.getStackTrace());
        }
    }

问题如下:

  • 我有10家公司的股票数据。
  • 每家公司都有一个符号名称。
  • 每个符号的计算数据存储在m_ListPrices中,其中每个键都是列名,每个值都是一个单元格值
    • 注意:直到运行时才知道列(即:基于用户选择的算法列名称和数字可能会有所不同)。

我有一个运行用户选择算法的计算器类。每个算法都有自己的输出,将其存储在上面的数据模型中。 我怎么可能将这个DataModel绑定到WPF中的DataGrid?

目前上面的代码给出了以下输出:

Grid Output

1 个答案:

答案 0 :(得分:0)

这就是我克服这个问题的方法: 我创建了一个DataTable作为我的数据网格的数据源,该数据网格填充了字典中的列。

                DataTable tbl = new DataTable();
            tbl.Columns.Add("Symbol Name", typeof(string));

            // Add columns
            foreach (InspectorOutput item in listScenarioOutput)
            {
                foreach (KeyValuePair<string, double> entry in item.ListPrices)
                {
                    tbl.Columns.Add(entry.Key, typeof(double));
                }
                break;
            }

            for (int i = 0; i < listScenarioOutput.Count; i++)
            {
                DataRow row = tbl.NewRow();
                row.SetField(0, listScenarioOutput[i].SymbolName);
                int j = 0;
                foreach (KeyValuePair<string, double> entry in listScenarioOutput[i].ListPrices)
                {
                    row.SetField(++j, entry.Value);
                }
                tbl.Rows.Add(row);
            }

            gridStockData.ItemsSource = tbl.DefaultView;