WPF ListBox ItemsSource StaticResource/Binding question
Asked Answered
B

1

10

Given the following code:

<Window x:Class="WpfApplication76.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <CollectionViewSource x:Key="myCol">
            <CollectionViewSource.Source>
                <col:ArrayList>
                    <ListBoxItem>Uno</ListBoxItem>
                    <ListBoxItem>Dos</ListBoxItem>
                    <ListBoxItem>Tres</ListBoxItem>
                </col:ArrayList>
            </CollectionViewSource.Source>
        </CollectionViewSource>
    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{StaticResource myCol}" />
        <ListBox ItemsSource="{Binding Source={StaticResource myCol}}" />
    </Grid>

</Window>

In this example, the

<ListBox ItemsSource="{StaticResource myCol}" />

Gives me an error complaining that it cannot bind to a "CollectionViewSource" object.

But the other listbox:

<ListBox ItemsSource="{Binding Source={StaticResource myCol}}" />

binds perfectly fine.

So my question is why does one work and the other one does not? AT the end, aren't both ItenSources being set to the same "CollectionViewSource" object?

Thank you.

Biak answered 17/9, 2009 at 21:54 Comment(0)
Z
7

The ItemsSource property is of type IEnumerable. A CollectionViewSource is not an IEnumerable. CollectionViewSource's View property will give you an IEnumerable.

When you Bind to a CollectionViewSource the Binding is smart enough to grab the View property and actually bind to that. Maybe CollectionViewSource has a [DefaultBindingProperty] on it.

It boils down to the fact that when you go through the Binding you don't actually bind to the CollectionViewSource, but its View property.

Zsigmondy answered 20/9, 2009 at 13:45 Comment(2)
Thanks Mike. I realize what the problem is. My question was really geared more toward why is the Binding taking the liberty of just picking a property from the “CollectionViewSource” object and just binging to that? I mean, why isn’t the “StaticResource” extension taking the liberty of doing the same thing too?Biak
Kind of guessing, but StaticResource is just saying "get me this thing" where as Binding is saying "get me something I can bind to". StaticResource is more literal. It has no context of usage whereas with Binding the system knows why your are asking for the resource. Chris Anderson's book, "Essential WPF" I think. Describes the order of things that happens when a Binding can't figure out exactly what to do. I don't have it handy but I'll try and look it up. It might say what happens in this case.Zsigmondy

© 2022 - 2024 — McMap. All rights reserved.