Andre Roque
Andre Roque

Reputation: 543

DataGrid bind to ObservableCollection

I'm trying to bind an ObservableCollection on my ViewModel to a DataGrid on my view:

public class RequestListViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Request> requests;
    private Timer uTimer;
    public RequestListViewModel()
    {
        requests = RequestAction.getRequestList();
        SetRequestsUpdateTimer();
    }

    public ObservableCollection<Request> Requests
    {
        get { return requests; }
        set { requests = value; OnPropertyChanged("Requests"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

This ObservableCollection is updated with a timer and is working fine. The data is updated. The problem is that update is not reflected on the view side:

<DataGrid Name="lstRequests" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="None" MouseDoubleClick ="myDataGrid_MouseDoubleClick" 
                  >
            <DataGrid.Columns>
...

            </DataGrid.Columns>

And I create the binding like this:

public RequestListView()
{
    InitializeComponent();
    model = new RequestListViewModel();
    //this.DataContext = model;
    lstRequests.ItemsSource = model.Requests;
    Binding myBinding = new Binding();
    myBinding.Source = model;
    myBinding.Path = new PropertyPath("Requests");
    myBinding.Mode = BindingMode.TwoWay;
    myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    lstRequests.SetBinding(DataGrid.ItemsSourceProperty, myBinding);
}

What am I missing here?

Upvotes: 1

Views: 961

Answers (1)

brunnerh
brunnerh

Reputation: 185479

Would only set DataContext if anything in code:

this.DataContext = model;
<DataGrid ItemsSource="{Binding Requests}" ... />

TwoWay and UpdateSourceTrigger is non-sense and does not apply for ItemsSource. If you change the DataContext along the hierarchy this binding will of course fail. Also, if you switch out your model completely and do not update the DataContext the binding will also no longer update.


From the comments it seems clear your problem is that you are misusing your code. Usually i prevent this whenever i use ObeservableCollections by making it read and get-only:

private readonly ObeservableCollection<...> _field = new ObeservableCollection<...>();
public ObeservableCollection<...> Property { get { return _field; } }

Upvotes: 1

Related Questions