wpf - ContentControl 崩溃中的绑定(bind)

标签 wpf xaml binding contentcontrol

谁能告诉我为什么这会使我的应用程序崩溃?我不知道为什么似乎有一些无休止的递归。我得到了这个异常(exception)

Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree


<ContentControl Content="{Binding}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Button Content="{Binding MyString}"/>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

这就是我作为来源的全部
    public MainWindow()
    {
        InitializeComponent();
        MyString = "Test";
        this.DataContext = this;
    }

    public string MyString { get; set; }

最佳答案

您使用 MainWindow 作为 MainWindow 内容的 DataContext。当您设置 Content="{Binding}"在 ContentControl 上,这是将 ContentControl 的内容设置为 MainWindow 实例。这是一个问题,因为 ContentControl 包含在 MainWindow 的内容中。每当 Content 属性接收到 UIElement 时,它都会将其呈现为 UIElement,而不是像使用非 UI 类那样通过 DataTemplate。所以你的树最终成为

MainWindow
 ContentControl
  MainWindow
   ContentControl
    ...

为您的 DataContext 使用单独的数据对象而不是窗口本身将为您提供您正在寻找的行为:
public partial class Window13 : Window
{
    public Window13()
    {
        InitializeComponent();
        MyData data = new MyData();
        data.MyString = "Test";
        this.DataContext = data;
    }
}

public class MyData
{
    public string MyString { get; set; }
}

关于wpf - ContentControl 崩溃中的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4519774/

相关文章:

WPF:堆栈面板中元素之间的间距

c# - WinRT 中 TextBlock 的外发光效果

c# - WPF 绑定(bind)到工具提示

c# - 防止最大化的 WPF 窗口覆盖任务栏

c# - 是否有Visual Studio之类的代码编辑器控件?

c# - 创建原始图形元素(无 Windows chrome)

c# - ItemsControl 中元素的 TranslateZoomRotateBehavior?

xaml - 如何使用 MVVM 模式将事件绑定(bind)到通用应用程序中的命令?

java - 有没有办法使用 GWT.create(...) 实例化泛型类型的类?

silverlight - 在 Silverlight 4 中使用值转换器绑定(bind)到 FontWeight