0

I have a window in which I want to autogenerate ObservableCollection from another class. When setting it up in back-end, everything works properly:

XAML

<DataGrid Name="ResidenceGrid" AutoGenerateColumns="True"/>

CS
public ResidenceWindow()
    {
        InitializeComponent();
        ResidenceGrid.ItemsSource = Manager.ResidenceList;
    }

But the moment I try to do it all in xaml, the DataGrid appears blank:

XAML

<DataGrid Name="ResidenceGrid" ItemsSource="{Binding Path=Manager.ResidenceList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True"/>

CS
public ResidenceWindow()
    {
        InitializeComponent();
    }

The ObservableCollection called from another class just in case:

static class Manager
{
    public static ObservableCollection<Residence> ResidenceList { get; set; } = new ObservableCollection<Residence>();
}

Any idea what I'm missing here?

Samuel Novelinka
  • 328
  • 3
  • 10

2 Answers2

2

If you want to use Binding, you need to set DataContext inside your ResidenceWindow.

Ex:

public ResidenceWindow()
{
    InitializeComponent();
    this.DataContext = Manager;
}

https://www.wpf-tutorial.com/data-binding/using-the-datacontext/

Nhan Phan
  • 1,262
  • 1
  • 14
  • 32
  • The Manager class is static though. If I try this, I get "Manager is a type, which is not valid in the given context." Any way to bypass this? I tried setting DataContext in MainWindow in xaml, but to no avail. No error, but empty DataGrid nonetheless. – Samuel Novelinka Aug 12 '18 at 11:25
  • You can try this: https://stackoverflow.com/questions/27880492/can-i-set-a-datacontext-to-a-static-class – Nhan Phan Aug 12 '18 at 11:27
1

You can bind to the static Manager.ResidenceList property like this:

<DataGrid Name="ResidenceGrid" ItemsSource="{x:Static local:Manager.ResidenceList}" AutoGenerateColumns="True"/>

And there is no reason to set the Mode of the binding for the ItemsSource property to TwoWay nor set the UpdateSourceTrigger to PropertyChanged.

mm8
  • 163,881
  • 10
  • 57
  • 88