【问题标题】:Frame navigation - DataContext not inherited框架导航 - 未继承 DataContext
【发布时间】:2012-02-17 23:19:12
【问题描述】:

我有一个表示 WPF 应用程序主窗口的 XAML 文件。 现在我希望此窗口显示由另一个 XAML 文件指定的内容。 这可行,但DataContext 在我的UserControl 的C# 代码中丢失了。

我认为<Frame Source=....> 在某种程度上破坏了 WPF 的逻辑树。 我希望具有与<Frame Source=....>Content1.xaml 文件内容简单替换的相同行为,即周围Window 类的DataContext 被继承到@ 987654329@.

有没有简单的方法来解决这个问题? 我发现的所有solutions 似乎都过分了。

伪代码

MainWindow.xaml

<Window ....>
    <Frame Source="Content1.xaml" />
</Window>

Content1.xaml

<UserControl ....>
  <!-- Content goes here -->
</UserControl>

【问题讨论】:

标签: wpf navigation frame datacontext


【解决方案1】:

Joe White 的解决方案here 解决了这个问题。

引用他的回答:

在 XAML 中:

<Frame Name="frame"
       LoadCompleted="frame_LoadCompleted"
       DataContextChanged="frame_DataContextChanged"/>

在代码隐藏中:

private void frame_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    UpdateFrameDataContext(sender, e);
}
private void frame_LoadCompleted(object sender, NavigationEventArgs e)
{
    UpdateFrameDataContext(sender, e);
}
private void UpdateFrameDataContext(object sender, NavigationEventArgs e)
{
    var content = frame.Content as FrameworkElement;
    if (content == null)
        return;
    content.DataContext = frame.DataContext;
}

【讨论】:

  • 您的参数有问题(无论如何都没有使用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2011-05-19
  • 2010-10-07
相关资源
最近更新 更多