ListView DynamicResource

1.5k views Asked by At

When attempting to use a DynamicResource as an ItemsSource for a ListView my application is outputting the error:

Window must be the root of the tree. Cannot add Window as a child of Visual.

If I was to remove the ItemsSource, and leave the code alone, then I dont get the error and an empty ListView will display.

My ListView located in my Window.XAML is as follows:

<ListView Grid.Column="1" Grid.Row="8" Grid.RowSpan="4" ItemsSource="{DynamicResource tasksResponsibilitiesCollection}">
                        <ListView.View>
                            <GridView AllowsColumnReorder="True">
                                <GridViewColumn DisplayMemberBinding="{Binding tasksResponsibilitiesName}" Header="Tasks/Responsibility" Width="150" />
                                <GridViewColumn Header="Member Responsible" Width="120" />
                                <GridViewColumn Header="Qualifications" Width="110" />
                            </GridView>
                        </ListView.View>
                    </ListView>

The ItemsSource is an ObservableCollection defined in the code-behind. I have been using the MSDN example (http://msdn.microsoft.com/en-us/library/ms747048.aspx) as my guide for the creation of the ListView

How do I go about bidning the ObservableCollection to the ListView? Do I have to define the resource within Window.XAML somewhere?

If there is anything that I haven't covered please let me know.

I appreciate your assistance,

Matt

1

There are 1 answers

0
Pavlo Glazkov On BEST ANSWER

If you ObservableCollection is defined as a property in the code-behind of the window then you could use data binding to set ItemsSource, like this:

<ListView Grid.Column="1" Grid.Row="8" Grid.RowSpan="4" ItemsSource="{Binding Path=tasksResponsibilitiesCollection, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
    <ListView.View>
        <GridView AllowsColumnReorder="True">
            <GridViewColumn DisplayMemberBinding="{Binding tasksResponsibilitiesName}" Header="Tasks/Responsibility" Width="150" />
            <GridViewColumn Header="Member Responsible" Width="120" />
            <GridViewColumn Header="Qualifications" Width="110" />
        </GridView>
    </ListView.View>
</ListView>

Please note that tasksResponsibilitiesCollection must be a public property in you window code-behind.