0

After being unsuccessful in databinding my Observable collection to my datagrid (Another question in this same forum), i tried to reduce the scope. Now my project has only one datagrid, one ObservableColection and one class. But still my databinding is failing.. please help..

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; }
    }
}

this is my 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>
Community
  • 1
  • 1
Ashutosh
  • 107
  • 1
  • 5

1 Answers1

0

You need to expose your ObservableCollection as a Property, not a Field.

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)
        });
    }
}

You cannot bind to fields, see here for some more information on the subject.

Community
  • 1
  • 1
Mike Eason
  • 9,525
  • 2
  • 38
  • 63