【问题标题】:StackOverflowException on InitializeComponentInitializeComponent 上的 StackOverflowException
【发布时间】:2011-04-27 16:08:36
【问题描述】:

我正在尝试关注 this little tutorial,但我不断收到此异常。

相关的 XAML 如下所示:

    <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 属性的合乎逻辑的地方,

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

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

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

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

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

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

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

    【讨论】:

    • 完美! NotifyPropertyChanged 的电话也很好。我发现我可以在你发布它之前一秒钟在代码隐藏中将 DataContext 设置为 this,但后来我遇到了你提到的问题。不过很容易通知~!
    【解决方案2】:

    理想情况下,您将绑定到的属性应该按照 MVVM 模式存在于 ViewModel 中,将自身从 View 中抽象出来。由于这不是您的问题,但是我们将继续前进…… DataContext 是从其父级继承的。因此,如果 StatusBar 存在于 Window 中,我很确定它确实存在,那么它将已经从 Window 继承 DataContext。您实际上是在尝试使用 UI 组件(窗口)作为 DataContext 的源来绑定 UI 组件。远非理想...这里是MVVM pattern的概述...

    【讨论】:

    • 只有在为 Window 设置的情况下,他才会从窗口继承 DataContext,并且不会通过使用 UIElement 本身的 DataContext 属性重置(他这样做)。
    • 我想我可以将 StatusBarText 放入它自己的 ViewModel 中。对于如此简单的事情,而且只有一个元素,这似乎有点过头了。
    • @Wonko 正确,这是他的 StackOverFlowException 的来源......这是他需要删除的内容,然后采取不同的方法。
    • @Mark 称它为 ViewModel,称它为 MyFancyClassThatIsNotAWindow...只是遵循奇怪的设计选择导致您进入异常...
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2013-07-11
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多