试图理解数据绑定(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/