7

给定以下代码:

<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>

在这个例子中,

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

给我一个错误,抱怨它无法绑定到“CollectionViewSource”对象。

但另一个列表框:

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

结合得很好。

所以我的问题是为什么一个有效而另一个无效?最后,不是两个 ItenSources 都设置为相同的“CollectionViewSource”对象吗?

谢谢你。

4

1 回答 1

5

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.

于 2009-09-20T13:45:09.970 回答