Tom Padilla
Tom Padilla

Reputation: 944

Binding to a copy of an ObservableCollection

I have an ObservableCollection bound to a DataGrid and everything works fine. I want to filter the collection without going to the database repeatedly so I decided to use a backing collection to store the original list and then publicly expose the filtered list to the binding. So I have the following code:

_backingMemberList.Clear();
_memberList.Clear();

foreach (Member CurrentMember in ListOfMembers)
{
    _memberList.Add(CurrentMember);
    _backingMemberList.Add(CurrentMember);
}

_memberList = new ObservableCollection<Member>(_backingMemberList);

and the binding is simply:

<DataGrid Name="dataGridMembers" ItemsSource="{Binding MemberList}" />

Now, for some reason this breaks the RowStyle

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="{Binding BindsDirectlyToSource=True, Converter={StaticResource BGColor}}"/>                                
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowStyle>

I don't get any information on the output pane about the binding being right or wrong. I can't figure out what I'm doing wrong.

And just to add to the fun I've got the same hookup on an other page and it breaks the binding altogether. The rows don't even show.

My questions are:

  1. What am I doing wrong?
  2. Failing that, how do I debug a data binding?

Upvotes: 0

Views: 1436

Answers (1)

Colin Smith
Colin Smith

Reputation: 12540

If could be this line that is causing your problems:

_memberList = new ObservableCollection<Member>(_backingMemberList);

by the looks of things you are overwriting the field (_memberList) which is presumably used by your property MemberList...with a different object instance...but the Binding is probably referring to the originally created one.....(your _memberList in the first half of the code is one instance....and then at the end of the code you set a new instance)...yes you are creating a shallow copy of the _backingMemberList...however you have changed _memberList...and need to tell the Binding to use the new instance of the collection.

You need to do an OnPropertyChanged("MemberList") to tell it that you changed the property....OR just don't do the "new"...as you already added the items to the collection by doing Clear() and Add() in your foreach.


Also going back to your explanation of why you are doing what you are doing...you might consider a different way to filter your collection.

Instead of making a copy, you could use a Filter on the CollectionViewSource which gets generated by WPF when your ItemsSource is bound to a collection. It sits between your ObservableCollection and the DataGrid.

Upvotes: 1

Related Questions