首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >InitializeComponent上的StackOverflowException

InitializeComponent上的StackOverflowException
EN

Stack Overflow用户
提问于 2010-10-20 03:08:56
回答 2查看 3K关注 0票数 2

我正在尝试遵循this little tutorial,但我总是得到这个异常。

相关的XAML如下所示:

代码语言:javascript
复制
    <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,是因为我试图使用MainWindow作为DataContext。我想使用MainWindow,因为它似乎是放置我的StatusBarText属性的合理位置,

代码语言:javascript
复制
public partial class MainWindow : Window
{
    public string StatusBarText { get; set; }

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

那我该怎么办?我应该把这个属性放在哪里?或者,有没有办法将DataContext设置为"this“,这样它就不会创建MainWindow的新实例,而只是引用它自己?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-20 03:16:00

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

代码语言:javascript
复制
public MainWindow()
{
    statusBar.DataContext = this;
}

请注意,在您所显示的代码示例中,您将只获得初始StatusBarText值,因为您没有实现INotifyPropertyChanged。

票数 3
EN

Stack Overflow用户

发布于 2010-10-20 03:15:30

理想情况下,您将绑定到的属性应该位于遵循MVVM模式的ViewModel中,将它们自身从视图中抽象出来。由于这不是您的问题,因此我们将移动along...the DataContext是从它的父级继承的。因此,如果StatusBar驻留在窗口中,那么它就已经从窗口继承了DataContext。您实际上是在尝试使用UI组件(窗口)作为DataContext的源来绑定UI组件。远离ideal...here的是MVVM pattern的概述...

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3971786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档