DataBind字符串到DataTemplated复选框

时间:2009-03-06 20:31:56

标签: wpf data-binding .net-3.5

我想在WPF中创建一个填充了复选框的ListBox,我想用简单的字符串值来数据化“Content”值。但是,当我尝试<CheckBox Margin="5" Content="{Binding}" />应用程序崩溃时。

这就是我所拥有的。 (我确定我错过了一些简单的事情)

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

1 个答案:

答案 0 :(得分:3)

您创建了一个无限递归的DataTemplate。通过设置DataTemplate for String,然后将CheckBox的内容设置为String,CheckBox将使用DataTemplate本身,因此您将在CheckBoxes中使用CheckBoxes,等等。

您可以通过在CheckBox中明确放置TextBlock来修复它:

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