StackOverflowException上的InitializeComponent [英] StackOverflowException on InitializeComponent

查看:227
本文介绍了StackOverflowException上的InitializeComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想跟随的这个小教程,但我不断收到此异常

I'm trying to follow this little tutorial, but I keep getting this exception.

有关XAML看起来像这样:

The relevant XAML looks like this:

    <StatusBar Margin="0,288,0,0" Name="statusBar" Height="23" VerticalAlignment="Bottom">
        <StatusBar.DataContext>
            <m:MainWindow />
        </StatusBar.DataContext>
        <TextBlock Name="statusText" Text="{Binding Path=StatusBarText, NotifyOnTargetUpdated=True}" DataContext="{Binding}">
            <TextBlock.Triggers>
                <EventTrigger RoutedEvent="Binding.TargetUpdated">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity">
                                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:0.25" Value="1"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:4" Value="1"/>
                                <EasingDoubleKeyFrame KeyTime="0:0:5" Value="0"/>
                            </DoubleAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </TextBlock.Triggers>
        </TextBlock>
    </StatusBar>



我猜我发现了 StackOverflowException 因为我尝试使用主窗口的DataContext 。我想使用主窗口,因为它好像把我的 StatusBarText 属性合乎逻辑的地方,

I'm guessing I'm getting the StackOverflowException because I'm trying to use MainWindow as the DataContext. I want to use the MainWindow because it seems like a logical place to put my StatusBarText property,

public partial class MainWindow : Window
{
    public string StatusBarText { get; set; }



这使得它更容易访问我的代码隐藏事件处理程序。

It makes it easier to access in my code-behind event handlers.

那我该怎么办呢?我应该在哪里把这个属性?还是有方法来设置的DataContext为本,这样它不创建主窗口的新实例,只是提到自己?

What am I supposed to do then? Where am I supposed to put this property? Or is there a way to set the DataContext to "this" so that it doesn't create a new instance of MainWindow and just refers to itself?

推荐答案

我一般设置我的代码隐藏的DataContext,在构造函数(我通常使用MVVM,但应用于小型临时项目窗口):

I generally set my DataContext in code-behind, in the constructor (I usually use MVVM, but have used a window in small temp projects):

public MainWindow()
{
    statusBar.DataContext = this;
}

请注意,在你所示的代码示例,你只会得到您的初始StatusBarText值因为你没有实现INotifyPropertyChanged的。

Note that in your shown code example, you will only get your initial StatusBarText value, because you are not implementing INotifyPropertyChanged.

这篇关于StackOverflowException上的InitializeComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆