我正在尝试遵循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的新实例,而只是引用它自己?
发布于 2010-10-20 03:16:00
我通常在代码隐藏中,在构造函数中设置我的DataContext (我通常使用MVVM,但在小型临时项目中使用窗口):
public MainWindow()
{
statusBar.DataContext = this;
}请注意,在您所显示的代码示例中,您将只获得初始StatusBarText值,因为您没有实现INotifyPropertyChanged。
发布于 2010-10-20 03:15:30
理想情况下,您将绑定到的属性应该位于遵循MVVM模式的ViewModel中,将它们自身从视图中抽象出来。由于这不是您的问题,因此我们将移动along...the DataContext是从它的父级继承的。因此,如果StatusBar驻留在窗口中,那么它就已经从窗口继承了DataContext。您实际上是在尝试使用UI组件(窗口)作为DataContext的源来绑定UI组件。远离ideal...here的是MVVM pattern的概述...
https://stackoverflow.com/questions/3971786
复制相似问题