当 WPF 列表框有一个按钮作为子项时,它会导致计算器溢出

WPF listbox is causing a stackoverflow when it has a button as a child

在尝试将按钮作为数据模板添加到列表框时,我 运行 进入了计算器。当改用文本框时,没有 Whosebug。是什么原因造成的?我正在使用 Visual Studios 2012 更新 4。

XAML代码:

<Window x:Class="WhosebugTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <ListBox ItemsSource="{Binding CausesWhosebug}">

        <ListBox.Resources>
            <DataTemplate DataType="{x:Type sys:String}">
                <Button Content="{Binding Path=.}"/>
            </DataTemplate>
        </ListBox.Resources>

    </ListBox>

</Window>

C#代码:

namespace WhosebugTest
{
    public partial class MainWindow
    {
        public string[] CausesWhosebug { get; set; }

        public MainWindow()
        {
            CausesWhosebug = new string[] { "Foo" };
            InitializeComponent();
            DataContext = this;
        }
    }
}

Button 是一个 ContentControl,它的内容也使用 DataTemplate。默认的 DataTemplate 最终以递归方式创建按钮以显示 "outer" 按钮的内容。

您应该明确设置 ListBox 的 ItemTemplate

<ListBox ItemsSource="{Binding CausesWhosebug}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>