0

I am a newbie to WPF so please excuse my ignorance. I have read online that inorder for binding to work, the observable collection should be a public property. So, here's what I have done so far:

I have a class in which I have declared the observable like this:

public ObservableCollection<InventoryDto> invCollection { get; set; }
 public InventoryDto()
        {
            invCollection = new ObservableCollection<InventoryDto>();
        }


        public ObservableCollection<InventoryDto> observableList
        {
            get
            {
                return this.invCollection;
            }
            set
            {
                invCollection = value;
                OnPropertyChanged("observableList");
            }
        }

Then, in my view, I have a binding like this:

ItemsSource="{Binding observableList,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

In the view's code behind (i.e, view.xamls.cs), I am populating the observable:

  foreach (var item in inventoryList)
            {

                invDto.invCollection.Add(new InventoryDto { location = item.location.Name, onHand = item.OnHand.ToString(), committed = item.committed.ToString() });


            }

However, I dont see any data in my grid unless I add this code:

 InventoryDataGrid.ItemsSource = invDto.observableList;

First, I find it odd to add this code in code behind whereas I have already specified ItemsSource in xaml. Second, this code populates the grid. But when I remove a row from db, the row does not get removed in the grid although I have specified BindingMode = TwoWay.

Please let me know what I am missing here.

mcfred
  • 1,183
  • 2
  • 29
  • 68
  • 1
    A Binding like `{Binding observableList}` without Source, RelativeSource or ElementName uses the current `DataContext` as source object. You should set the MainWindow's DataContext to an instance of your InventoryDto class. Besides that, setting `Mode=TwoWay` and `UpdateSourceTrigger=PropertyChanged` is pointless. It has no effect here. You should also not use a public property as "backing field" of another public property. I.e. `invCollection` should be a private field. – Clemens Jul 24 '18 at 07:20
  • I am not sure why you marked it as a duplicate bcs I honestly didn't understand the other thread. Anyways, so when you say that I should set the mainwindow's datacontext to an instance of inventorysto, do you mean something like this: DataContext="{Binding invDto}" ? – mcfred Jul 24 '18 at 07:31
  • 1
    As said, "set the MainWindow's DataContext to an instance of your InventoryDto class", e.g. `DataContext = new InventoryDto();` in the MainWindow's constructor. Before continuing, read [Data Binding Overview](https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-binding-overview). – Clemens Jul 24 '18 at 07:36

0 Answers0