简体   繁体   English

将CollectionViewSource绑定到ListBox

[英]Binding a CollectionViewSource to a ListBox

For some reason I cannot get my ListBox to display data from my CollectionViewSource . 出于某种原因,我无法让我的ListBox显示来自我的CollectionViewSource数据。 Here is the code... 这是代码......

public class AppTest
{
    public int Priority { get; set; }
    public string TestName { get; set; }
}

public class AppTestProvider
{
    public List<AppTest> GetAppTests()
    {
        return new List<AppTest>()
        {
            new AppTest() { Priority=1, TestName = "Application Setup" },
            new AppTest() { Priority=2, TestName = "File System Permissions" }
        };
    }
}

... and now the Xaml... ......现在是Xaml ......

<Window.Resources>
    <ObjectDataProvider x:Key="AppTests" ObjectType="{x:Type Application:AppTestProvider}" MethodName="GetAppTests" />
    <CollectionViewSource x:Key="cvs" Source="{Binding AppTests}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Priority" Direction="Ascending" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>

<Grid>
    <ListBox x:Name="TestList" ItemsSource="{Binding Source={StaticResource cvs}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding TestName}" />                    
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

If I change the ItemsSource of the ListBox to look like this (getting data from the ObjectDataSource and not the CVS) it displays the data albeit not sorted... 如果我将ListBoxItemsSource更改为这样(从ObjectDataSource不是 CVS获取数据),它会显示数据,尽管没有排序...

<ListBox x:Name="TestList" ItemsSource="{Binding Source={StaticResource AppTests}}">

I'm sure this must be something pretty simple. 我相信这一定很简单。 I just cannot seem to get it to work! 我似乎无法让它工作!

Replace this <CollectionViewSource x:Key="cvs" Source="{Binding AppTests}"> 替换此<CollectionViewSource x:Key="cvs" Source="{Binding AppTests}">

with <CollectionViewSource x:Key="cvs" Source="{StaticResource AppTests}"> . 使用<CollectionViewSource x:Key="cvs" Source="{StaticResource AppTests}">

You are referring to resource defined in XAML so you need to use StaticResource instead of Binding to refer to ObjectDataProvider just like you are doing in later approach to set ItemsSource of your listBox. referring to resource在XAML中定义的referring to resource ,因此您需要使用StaticResource而不是Binding来引用ObjectDataProvider ,就像您在稍后设置listBox的ItemsSource时所做的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM