Marija Rakic
Marija Rakic

Reputation: 140

How to bind ObservableCollection to the ListView in a UserControl?

I have the following xaml file:

<Page ...>
    <Grid>
        <ListView ItemsSource="{Binding MissingValues}">
            <ListView.View>
                <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Information on Missing Values">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=Element.Name}" Header="Element" Width="100" />
                    <GridViewColumn DisplayMemberBinding="{Binding Path=Description}" Header="Description" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

Code behind is only:

DataContext = new MyViewModel();

And MyViewModel has public ObservableCollection<MissingValue> MissingValues initialized in the constructor. On the button click, items are added to this property and everything works as exptected.

Since the xaml file became too big, i wanted to make it smaller and easier to manage by extracting this ListView in a UserControl called MissingValuesListView and invoking it using the following code:

<local:MissingValuesListView></local:MissingValuesListView>

However, the list is no longer updated when the new elements are added.

MissingValuesListView's code behind contains only DataContext = new MyViewModel();.

I don't think it's of any relevance (since the code works when part of the main xaml file, but not when moved to UserControl), but both MyViewModel and MissingValue implment INotifyPropertyChanged.

My question is why is this not working? I assume i'm missing some code or some binding, but i failed to find out what. Any help is highly appreciated!

Upvotes: 0

Views: 632

Answers (1)

mm8
mm8

Reputation: 169150

MissingValuesListView's code behind contains only DataContext = new MyViewModel();.

It shouldn't. Try to remove this line. You should simply copy the following XAML into MissingValuesListView.xaml and replace it with <local:MissingValuesListView /> in the current XAML file:

<ListView ItemsSource="{Binding MissingValues}">
    <ListView.View>
        <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Information on Missing Values">
            <GridViewColumn DisplayMemberBinding="{Binding Path=Element.Name}" Header="Element" Width="100" />
            <GridViewColumn DisplayMemberBinding="{Binding Path=Description}" Header="Description" />
        </GridView>
    </ListView.View>
</ListView>

If you do this, the UserControl will inherit the DataContext where the MissingValues property is defined from its parent element and the binding should work just like before.

Upvotes: 1

Related Questions