使用Dictionary项在WPF中填充DataGrid

时间:2014-03-11 17:37:59

标签: c# wpf dictionary datagrid

我有DictionaryPointCoordinate个对象作为值。

Dictionary<string, PointCoordinate> PointCoordinates;

我的PointCoordinate课程定义如下:

class PointCoordinate
{
    public double X { get; set; }
    public double Y { get; set; }
}

如何使用对象的DataGridWPFKeys属性填充X中的Y

1 个答案:

答案 0 :(得分:0)

    using System.Collections.Generic;
    using System.Windows;

    namespace WpfApplication1 {

        public class PointCoordinate {
            public double X { get; set; }
            public double Y { get; set; }
        }

        public class PointCoordinate2 : PointCoordinate {
            public string key { get; set; }
        }

        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();

                Dictionary<string, PointCoordinate> PointCoordinates = new Dictionary<string, PointCoordinate>();
                PointCoordinates.Add("Number 1", new PointCoordinate() { X = 1, Y = 4 });
                PointCoordinates.Add("Number 2", new PointCoordinate() {X = 2, Y = 5});
                PointCoordinates.Add("Number 3", new PointCoordinate() {X = 3, Y = 6});

                List<PointCoordinate2> lList = new List<PointCoordinate2>();
                foreach (var lItem in PointCoordinates) {
                    PointCoordinate2 lPC2 = new PointCoordinate2();
                    lPC2.key = lItem.Key;
                    lPC2.X = lItem.Value.X;
                    lPC2.Y = lItem.Value.Y;
                    lList.Add(lPC2);
                }
                //var n = from x in PointCoordinates select ;
                myDataGrid.AutoGenerateColumns = true;
                myDataGrid.ItemsSource = lList;
            }
        }
    }

这不是对原始数据的数据绑定。然而,它确实正确显示数据。有关数据绑定的更多信息,请访问:http://csharphardcoreprogramming.wordpress.com/2014/02/20/data-binding-part-1-advanced-wpf/