【问题标题】:Databinding a Datagrid数据绑定数据网格
【发布时间】:2015-06-13 06:55:41
【问题描述】:

在将我的 Observable 集合数据绑定到我的数据网格 (Another question in this same forum) 失败后,我试图缩小范围。现在我的项目只有一个数据网格、一个 ObservableColection 和一个类。 但我的数据绑定仍然失败..请帮助..

using System.Collections.ObjectModel;
using System.Windows;

namespace TestDatagrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainViewModel
    {
        public ObservableCollection<OptionStrike> oOs = new ObservableCollection<OptionStrike>(new OptionStrike[]
            {
                new OptionStrike("Put", 7500.00, 12345),
                new OptionStrike("Call", 7500.00, 123),
                new OptionStrike("Put", 8000.00, 23645),
                new OptionStrike("Call", 8000.00,99999)
            });
    }

    public class OptionStrike
    {
        public OptionStrike(string p1, double p2, int p3)
        {
            // TODO: Complete member initialization
            this.Type = p1;
            this.Strike = p2;
            this.Volume = p3;
        }

        public string Type { get; set; }
        public double Strike { get; set; }
        public double Volume { get; set; }
    }
}

这是我的 XAML..

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestDatagrid" x:Class="TestDatagrid.MainWindow" Title="MainWindow" Height="350" Width="525">
  <Window.DataContext>
    <local:MainViewModel/>
  </Window.DataContext>
  <Grid>
    <StackPanel>
      <DataGrid ItemsSource="{Binding oOs}" AutoGenerateColumns="True" />
    </StackPanel>
  </Grid>
</Window>

【问题讨论】:

    标签: c# wpf data-binding datagrid


    【解决方案1】:

    您需要将您的ObservableCollection 公开为属性,而不是字段

    public class MainViewModel
    {
        public ObservableCollection<OptionStrike> oOs { get; set; }
    
        public MainViewModel()
        {
            oOs = new ObservableCollection<OptionStrike>(new OptionStrike[]
            {
                new OptionStrike("Put", 7500.00, 12345),
                new OptionStrike("Call", 7500.00, 123),
                new OptionStrike("Put", 8000.00, 23645),
                new OptionStrike("Call", 8000.00,99999)
            });
        }
    }
    

    您无法绑定到字段,有关该主题的更多信息,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2011-09-28
      • 2012-10-29
      相关资源
      最近更新 更多