WPF DataGrid - 绑定到'单元格'的集合 [英] WPF DataGrid - Bind to collection of 'cells'

查看:157
本文介绍了WPF DataGrid - 绑定到'单元格'的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何将DataGrid的数据源绑定到'cells'的ObservableCollection。特别是,我有一个ObservableCollection,它包含以下类的实例:

I'm trying to figure out how to bind the datasource of a DataGrid to an ObservableCollection of 'cells'. In particular, I have an ObservableCollection that holds instances of the following class:

public class Option : INotifyPropertyChanged
{
    public Option()
    {
    }

    // +-+- Static Information +-+-
    public double spread = 0;        
    public double strike = 0;        
    public int daysToExpiry = 0;
    public int put_call; // 0 = Call, 1 = Put

    // Ticker References
    public string fullTicker = "";
    public string underlyingTicker = "";

    //+-+-Properties used in Event Handlers+-+-//
    private double price = 0;
    public double Price
    {
        get { return price; }
        set
        {
            price = value; 
            NotifyPropertyChanged("Price");
        }
    }

    //+-+-+-+- Propoerty Changed Event & Hander +-+-+-+-+-//
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

在我的DataGrid上,我想显示这些类(我使用TemplateColumns的价格和每个单元格中的'strike'变量),以便它们被底层标签[这是一个4字符串]和扩展分组6个后台编码中定义的可能值]。

On my DataGrid, I want to display these classes (I'm using TemplateColumns the Price and the 'strike' variables in each cell) such that they are grouped by "underlyingTicker" [which is a 4 character string] and by "spread" [which takes on 1 of 6 possible values defined in the background coding].

目前,当我将DataGrid的DataContext绑定到ObservableCollection时,它将每个Option显示为一行 - 我无法弄清楚如何指定要分组的内容在...上的对...

Currently, when I bind the DataGrid's DataContext to the ObservableCollection, it shows each 'Option' as a row - and I can't figure out how to specify what to group the pairs on...

这是我的datagrid现在的样子:

This is what my datagrid looks like now:

非常感谢 - kcross!

Thanks a lot - kcross!

推荐答案

像Dtex一样,我不完全明白你想做什么。但是我试图做一个简化,希望能让你开始。
您必须通过 DataGrid 一个 IEnumerable (最好是 ObserrvableCollection )对象。单个对象将转换为行,这些对象的属性将转换为列标题。

Like Dtex I do not entirely understand what you want to do. But I tried to make a simplification that hopefully will get you started. You have to pass the DataGridan IEnumerable(preferably an ObserrvableCollection) of objects. The individual objects will translate to rows, the properties of these objects will translate to the column headers.

因此,如果希望列标题代表标准偏差的倍数(对吗?)您将必须创建一个具有这些倍数作为属性的对象。所得到的单元格将包含 Option 类。要表示这些,您将必须定义一个DataTemplate或覆盖ToString()函数。我认为你是从你的例子中做出的。

So if you want the column headers to represent multiples of the standard deviation (right?) you will have to create an object that has these multiples as properties. The resulting cells will contain the Option classes. To represent these you will have to define a DataTemplate or override the ToString() function. I think you did the former judging from your example.

后面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace DataGridSpike
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<Option> _unsortedOptions;
        private ObservableCollection<OptionRow> _groupedOptions;

        public ObservableCollection<OptionRow> GroupedOptions
        {
            get { return _groupedOptions; }
            set { _groupedOptions = value; }
        }

        public MainWindow()
        {
            var rnd=new Random();
            InitializeComponent();

            //Generate some random data
            _unsortedOptions=new List<Option>();
            for(int element=0;element<50;element++)
            {
                double column=rnd.Next(-2,3);
                int row=rnd.Next(0,9);

                _unsortedOptions.Add(new Option { ColumnDefiningValue = column, RowDefiningValue = row });
            }

            //Prepare the data for the DataGrid
            //group and sort
            var rows = from option in _unsortedOptions
                       orderby option.ColumnDefiningValue
                       group option by option.RowDefiningValue into optionRow
                       orderby optionRow.Key ascending
                       select optionRow;

            //convert to ObservableCollection
            _groupedOptions = new ObservableCollection<OptionRow>();
            foreach (var groupedOptionRow in rows)
            {
                var groupedRow = new OptionRow(groupedOptionRow);
                _groupedOptions.Add(groupedRow);
            }

            //bind the ObservableCollection to the DataGrid
            DataContext = GroupedOptions;
        }
    }

    public class OptionRow
    {
        private List<Option> _options;

        public OptionRow(IEnumerable<Option> options)
        {
            _options = options.ToList();
        }

        public Option Minus2
        {
            get
            {
                return (from option in _options
                       where option.ColumnDefiningValue == -2
                       select option).FirstOrDefault();
            }
        }
        public Option Minus1
        {
            get
            {
                return (from option in _options
                        where option.ColumnDefiningValue == -1
                        select option).FirstOrDefault();
            }
        }
        public Option Zero
        {
            get
            {
                return (from option in _options
                        where option.ColumnDefiningValue == 0
                        select option).FirstOrDefault();
            }
        }
        public Option Plus1
        {
            get
            {
                return (from option in _options
                        where option.ColumnDefiningValue == 1
                        select option).FirstOrDefault();
            }
        }
        public Option Plus2
        {
            get
            {
                return (from option in _options
                        where option.ColumnDefiningValue == 2
                        select option).FirstOrDefault();
            }
        }
    }

    public class Option:INotifyPropertyChanged
    {

        public override string ToString()
        {
            return string.Format("{0}-{1}", RowDefiningValue.ToString(),ColumnDefiningValue.ToString());
        }

        private double _columnDefiningValue;
        public double ColumnDefiningValue
        {
            get{return _columnDefiningValue;}
            set{_columnDefiningValue = value;
                OnPropertyChanged("ColumndDefiningValue");
            }
        }

        private int _rowDefiningValue;
        public int RowDefiningValue
        {
            get{return _rowDefiningValue;}
            set{_rowDefiningValue = value;
                OnPropertyChanged("RowDefiningValue");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

XAML:

<Window x:Class="DataGridSpike.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid ItemsSource="{Binding}"/>
    </Grid>
</Window>

这篇关于WPF DataGrid - 绑定到'单元格'的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆