Issue with lists / collections of string

28 08 2012

I did some development for Windows 8 in the last couple of weeks and came across an issue which I want to share with you.

I’m currently working on Windows 8 Release Preview with Visual Studio 2012 RC installed. Hopefully the issue is fixed inside the final version.

Let’s start with some code to demonstrate the issue. Create a simple list with string elements on the view model

MyList = new List<string> { "Test1", "Test2", string.Empty };

The next step is to bind this property to a GridView. We start by creating a CollectionViewSource which we can bind to a GridView.

<Grid>
    <Grid.Resources>
        <CollectionViewSource
            x:Name="MyListViewSource"
            Source="{Binding MyList}"/>
    </Grid.Resources>
    <GridView
        Background="Green"
        ItemsSource="{Binding Source={StaticResource MyListViewSource}}"
        SelectionMode="None">
        <GridView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"></TextBlock>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</Grid>

When I executed the code, I expected something like the following result (3 GriedView items, 2 with text and 1 with an empty text):

image

But the rendered result was different:

image

Every GridView item which is bound to string.Empty is rendered a black box.

A workaround for this issue is to create a simple class with a string property (don’t forget to update the binding).

MyList = new List<MyClass> {
    new MyClass { StringValue = "Test1"} ,
    new MyClass { StringValue = "Test2"},
    new MyClass { StringValue = string.Empty }
};

I know this isn’t nice but a workaround until the issue is fixed.