c# - InitializeComponent 在绑定(bind)时触发 StackOverflow 异常

标签 c# wpf xaml data-binding

试图理解数据绑定(bind),这似乎完全是一个菜鸟错误,但我不知道为什么会这样。

CS

namespace MuhProgram
{
    public partial class MainWindow : Window
    {
        public string foobar
        {
            get { return "loremipsum"; }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

XAML:

<Window x:Class="MuhProgram.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MuhProgram"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
         <local:MainWindow x:Key="classMainWindow"/>
    </Window.Resources>

    <Grid>
        <Label Content="{Binding Source={StaticResource classMainWindow}, Path=foobar}"></Label>
    </Grid>
</Window>

调试器指向 InitializeComponent() 调用 MainWindow() 方法并引发 StackOverflowException。

我也尝试在网格中将 DataContext 属性设置为 "{StaticResource classMainWindow}" 但效果是一样的。

最佳答案

引发了 StackOverflow 异常,因为您在这一行递归创建了 MainWindow 的实例

<local:MainWindow x:Key="classMainWindow"/>

当调用 InitializeComponent() 时,它将初始化 XAML 并从已编译的 BAML 加载它。加载时发现 Label Content 需要 MainWindow 的另一个实例来绑定(bind)它的 Content DP。因此,它将递归地创建 MainWindow,直到它因 SO 异常而崩溃。


您不需要声明 MainWindow 的另一个实例。像这样将标签绑定(bind)到父实例:

<Label Content="{Binding Path=foobar, RelativeSource={RelativeSource FindAncestor, 
                                                            AncestorType=Window}}"/>

要么将 DataContext 设置为自身,让 Label 从父窗口继承它。

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
  ....
  <Label Content="{Binding foobar}"/>

在窗口上设置 x:Name 并使用 ElementName 进行绑定(bind)。

<Window x:Name="myWindow">
   .....
   <Label Content="{Binding foobar, ElementName=myWindow}" />

关于c# - InitializeComponent 在绑定(bind)时触发 StackOverflow 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26175412/

相关文章:

c# - 为扫雷游戏动态创建一个游戏板

.net - WPF/Silverlight 文本效果

Silverlight 验证不适用于数据注释

c# - Windows 服务中的可重入计时器

c# - 为什么 C# 支持抽象成员的抽象覆盖?

sql-server - 使用 WPF 数据网格更新 SQL 数据库表

c# - 访问 C# WPF 应用程序中的资源(同一程序集)

c# - 如何在 Entity Framework 中获取实体的某些列?

c# - 为什么在DisplayNameFor()中需要lambda表达式?

c# - 在 WPF 中单击更改圆圈 "start-stop"按钮背景图像