zak zak
zak zak

Reputation: 129

WPF - Update Datagrid in ObservableCollection

My datagrid view doesn't update when the source is modified.

In my View.xaml :

<DataGrid IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Single" ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" SelectedItem="{Binding SelectedItem}">
   <DataGrid.Columns>
       <DataGridTextColumn Header="Date" Width="*" Binding="{Binding ProductHistoryInOutDate}" />
       <DataGridTextColumn Header="Quantité" Width="*" Binding="{Binding ProductHistoryQuantity}" />
   </DataGrid.Columns>
</DataGrid>

In my ViewModel.cs :

private ObservableCollection<ProductHistory> _Items;

public ObservableCollection<ProductHistory> Items
{
    get { return _Items; }
    set 
    { 
         _Items = value;
         RaisePropertyChanged("Items");
    }
}

[Edit]

Command:

public RelayCommand Remove
{
    get
    {
        if (_Remove == null)
        {
            _Remove = new RelayCommand(
                () => { _UOF.ProductHistoryRepository.Delete(this.SelectedItem);_UOF.Commit(); },
                () => SelectedItem != null);
        }

        return _Remove;
    }
}

Remove button:

<Button Content="Delete" Command="{Binding Path=Remove}" />

Upvotes: 0

Views: 750

Answers (1)

mrzli
mrzli

Reputation: 17369

The only explanation I can think of is that you are missing Items.Remove(this.SelectedItem) in your command execute code.

I tried making and example from your code and it worked fine if I added this, there was no issue with observable collection.

Since I don't have your code for RelayCommand and RaisePropertyChanged(), I had to manually implement it to try it out, but I assume it is from some library and it works fine.

Here is what it should look like:

public RelayCommand Remove
{
    get
    {
        if (_Remove == null)
        {
            _Remove = new RelayCommand(
                () => { Items.Remove(this.SelectedItem); _UOF.ProductHistoryRepository.Delete(this.SelectedItem); _UOF.Commit(); },
                () => SelectedItem != null);
        }

        return _Remove;
    }
}

Upvotes: 2

Related Questions