试图理解数据绑定,这似乎完全是一个新手的错误,但我不知道为什么会发生。
政务司司长
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}",但效果是相同的。
发布于 2014-10-03 08:10:21
引发StackOverflow异常是因为在该行中递归地创建MainWindow实例。
<local:MainWindow x:Key="classMainWindow"/>当InitializeComponent()被调用时,它将初始化XAML并从编译的BAML加载它。在加载时,它找到的标签内容需要MainWindow的另一个实例来绑定它的内容DP。因此,它将递归地创建MainWindow,直到它以这样的异常崩溃。
不需要声明MainWindow的另一个实例。将标签绑定到父实例,如下所示:
<Label Content="{Binding Path=foobar, RelativeSource={RelativeSource FindAncestor,
AncestorType=Window}}"/>或
要么将DataContext设置为自身,然后让Label从父窗口继承它。
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
....
<Label Content="{Binding foobar}"/>或
设置x:在窗口上命名并使用ElementName绑定。
<Window x:Name="myWindow">
.....
<Label Content="{Binding foobar, ElementName=myWindow}" />https://stackoverflow.com/questions/26175412
复制相似问题