ContentControl 中的绑定崩溃
谁能告诉我为什么这会使我的应用程序崩溃?似乎有一些无休止的递归,我不明白为什么。我得到这个例外
逻辑树深度超出范围 遍历树。这可以 表示树中的一个循环
<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; }
Can anyone tell me why this crashes my app? There seems to be some endless recursion by I can't figure out why. I get this 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>
And this is all I have as Source
public MainWindow()
{
InitializeComponent();
MyString = "Test";
this.DataContext = this;
}
public string MyString { get; set; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用 MainWindow 作为 MainWindow 内容的 DataContext。当您在 ContentControl 上设置
Content="{Binding}"
时,这会将 ContentControl 的内容设置为 MainWindow 实例。这是一个问题,因为 ContentControl 包含在 MainWindow 的 Content 中。每当 Content 属性接收 UIElement 时,它都会将其呈现为 UIElement,而不是像非 UI 类那样通过 DataTemplate。因此,您的树最终会为您的 DataContext 使用单独的数据对象而不是窗口本身将为您提供您正在寻找的行为:
You're using MainWindow as the DataContext of the MainWindow's content. When you set
Content="{Binding}"
on the ContentControl this is setting the ContentControl's content to the MainWindow instance. This is a problem because the ContentControl is contained in the MainWindow's Content. Whenever a Content property receives a UIElement, it renders it as a UIElement, not through the DataTemplate as it would with an non-UI class. So your tree ends up beingUsing a separate data object for your DataContext instead of the window itself will give you the behavior you're looking for:
尽管我完全同意您不应该这样做的公认答案,但有时您只是没有选择。例如,我正在使用 Xceed PropertyGrid 和
DataContext
我为网格的每个项目都有一个PropertyItem
,它是一个UIElement
(包含Value
成员中的实际数据)。我发现的解决方法是使用
ContentPresenter
而不是ContentControl
。文档对此并不清楚,但似乎UIElement
是模板化的,而不是按原样使用。Although I totally agree with the accepted answer that you should not do this, sometimes you just don't have the choice. For instance, I'm using Xceed PropertyGrid and the
DataContext
I have for each item of the grid is aPropertyItem
which is aUIElement
(containing the actual data in aValue
member).The workaround I found is to use a
ContentPresenter
instead of aContentControl
. The documentation is not clear about this but it seems thatUIElement
are templated instead of being used as-is.您应该删除 ContentControl 的 Content 属性上的绑定。无论如何,这应该做什么?
You should remove the binding on the Content property of the ContentControl. What is this supposed to do anyway?