【问题标题】:How can I change a "Frame Content" in another class? (C# WPF XAML)如何更改另一个类中的“框架内容”? (C# WPF XAML)
【发布时间】:2021-10-15 10:34:06
【问题描述】:

有一次解释一下,我通过“frame.content”打开了一个 xaml 页面,在我打开的这个页面中,我想打开另一个页面,但是在第二个页面正在运行的框架上。 但我无法打开页面,

什么都没有发生。甚至没有期望。

所以我写的是:


这是打开的页面中的类

private void bttn_start(object sender, RoutedEventArgs e)
{
   MainWindow mw = new MainWindow();
   mw.JoinNextPage();
}

这是框架所在的 MainWindow 类。

public partial class MainWindow : Window
{ 
   public void JoinNextPage() => pageMirror.Content = new page_finish();
}

如果有任何有用的提示,我将不胜感激,因为昨天我花了几个小时在互联网上寻找,却一无所获。

【问题讨论】:

  • 问题不清楚。
  • @BionicCode Wie meinen sie das? Ich kann halt nicht extern auf einem Frame zugreifen。还有 den “内容” ändern。
  • 不清楚要从哪里显示页面。 JoinNextPage 会失败吗?
  • @BionicCode 好吧,我创建了一个程序,您可以在其中浏览页面。为此,我采用了“”并将其命名为“pageMirror”。在此框架上将显示 XAML 页面。这也有效,但是当我想从我调用的页面调用另一个页面时,什么也没有发生。它转到函数但没有执行任何操作。但是当我在内部执行此操作时,一切正常,但在外部我的“请求”无处可去。当我在外部执行时,我的对象总是被定义为“null”。
  • 我可以显示所有页面(只要我在“”所在的类中),但是只要我想从外部访问它,我的对象总是定义为“空”。

标签: c# wpf xaml mvvm


【解决方案1】:

试试这个:

private void bttn_start(object sender, RoutedEventArgs e)
{
   MainWindow mw = (MainWindow)Application.Current.MainWindow;
   mw.JoinNextPage();
}

【讨论】:

  • 最好使用页面的 NavigationService 而不是依赖于 MainWindow(或一般的外部 Window)中的方法。这就是服务的目的。它有助于将页面与托管视图分离。
  • 太棒了,所以有效。
【解决方案2】:

您应该使用RoutedCommand 来触发Frame 导航而不是静态MainWindow 引用。

这会从您的页面中删除完整的导航逻辑(按钮事件处理程序)。

MainWindow.xaml.cs

public partial class MainWindow : Window
{
  public static RoutedCommand NextPageCommand { get; } = new RoutedCommand("NextPageCommand", typeof(MainWindow));

  public MainWindow()
  {
    InitializeComponent();

    CommandBindings.Add(
      new CommandBinding(NextPageCommand, ExecuteNextPageCommand, CanExecuteNextPageCommand));      
   }

  private void CanExecuteNextPageCommand(object sender, CanExecuteRoutedEventArgs e)
  {
    e.CanExecute = true;
  }

  private void ExecuteNextPageCommand(object sender, ExecutedRoutedEventArgs e)
  {
    // Logic to select the next Frame content
    JoinNextPage();
  }
}

MainWindow.xaml

<Window>
  <Frame>
   <Frame.Content>
     <Page>
       <Button Command="{x:Static local:MainWindow.NextPageCommand}" 
               Content="Next Page" />
      </Page>
    </Frame.Content>
  </Frame>
</Window>

【讨论】:

  • 看起来很有趣,但我得到“错误 XDG0012 未检测到元素“NextPageCommand”,或者无法访问该元素。”
  • 你定义命令静态了吗?上面的“示例”不包括 XAML 中的命名空间定义。例如,您需要定义xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 才能使用x:Static
  • 你没有使用NavigationService,你只是使用命令调用他的方法。 docs.microsoft.com/en-us/dotnet/api/…
  • @DarkTemplar 是的,非常正确。我选择使用 RoutedCommand 以便从页面中完全删除导航逻辑(这使得 Button.Click 处理程序已过时 - 除了删除对 MainWindow 的引用)。
  • @BionicCode 谢谢,这实际上是最好的主意,而且更干净。祝你有美好的一天
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
相关资源
最近更新 更多