views:

341

answers:

1

I want to create a ListBox filled with checkboxes in WPF, and I want to databind the "Content" value with a simple string value. However when I try <CheckBox Margin="5" Content="{Binding}" /> the app crashes.

This is what I have. ( I'm sure I am missing something simple )

<ListBox Grid.Row="1" IsSynchronizedWithCurrentItem="True" x:Name="drpReasons">
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel Orientation="Horizontal" >
                            </WrapPanel>
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.Resources>
                        <DataTemplate DataType="{x:Type System:String}">
                            <CheckBox Margin="5" Content="{Binding}" />
                    </DataTemplate>
                    </ListBox.Resources>
                </ListBox>
+2  A: 

You created an infinitely recursive DataTemplate. By setting the DataTemplate for String, and then setting the Content of CheckBox to a String, the CheckBox will use the DataTemplate itself, so you'll have CheckBoxes within CheckBoxes and so on.

You can fix it by putting a TextBlock inside the CheckBox explicitly:

<ListBox x:Name="drpReasons" Grid.Row="1" IsSynchronizedWithCurrentItem="True">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal">
            </WrapPanel>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
            <CheckBox Margin="5">
                <TextBlock Text="{Binding}"/>
            </CheckBox>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>
Robert Macnee
I knew it would be something simple. Thanks!
Russ