Remotec
Remotec

Reputation: 10782

Binding a CollectionViewSource to a ListBox

For some reason I cannot get my ListBox to display data from my 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...

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

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

Upvotes: 3

Views: 5144

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81333

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

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

Upvotes: 5

Related Questions