c# - wpf中页面之间的通信

标签 c# wpf frames communicate

我有两个页面和一个主窗口。我在两个框架中加载页面。现在我想执行彼此的方法。我该怎么做?

这是 Page1.cs:

public partial class Page1 : Page
{
    public Method1()
    {
        doSomething;            
    }
}

这是 Page2.cs:

public partial class Page2 : Page
{
    public Method2()
    {
        doSomethingElse;            
    }
}

在我的主窗口中发生以下情况:

Frame1.Source = new Uri("/Source/Pages/Page1.xaml", UriKind.RelativeOrAbsolute);
Frame2.Source = new Uri("/Source/Pages/Page2.xaml", UriKind.RelativeOrAbsolute);

有什么方法可以从 Page1.cs 执行 Method2,从 Page2.cs 执行 Method1?

问候

最佳答案

实现此目的的一种方法是通过它们的共同父级窗口。

看这个(相应修改)

public partial class MainWindow : Window
{
    public Page1 Page1Ref = null;
    public Page1 Page2Ref = null;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Frame1.Source = new Uri("/Source/Pages/Page1.xaml", UriKind.Relative);
        Frame1.ContentRendered += Frame1_ContentRendered;

        // do the same for the Frame2
    }

    private void Frame1_ContentRendered(object sender, EventArgs e)
    {
        var b = Frame1.Content as Page1; // Is now Home.xaml
        Page1Ref = b;
        if(Page2Ref != null) // because you don't know which of the pages gets rendered first
        {
           Page2Ref.Page1Ref = Page1Ref; // add the Page1Ref prop to your Page2 class 
           Page1Ref.Page2Ref = Page2Ref;  // here the same
        }

    }
    // do the same for the other page
}

来自 this question

您应该能够在一个页面加载到另一个页面后设置引用。

更好的是,您可能想让页面知道它们的窗口父级并通过它访问其他页面。无论哪种方式,都是糟糕的设计,我告诉你。

这不是一个值得骄傲的解决方案,您最好研究一下 MVVM,然后使用它。 让我知道它是否适合您。

关于c# - wpf中页面之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802911/

相关文章:

c# - WPF - 在 Window 类中对方法进行单元测试时出现 XamlParseException

html - 删除 HTML 框架

javascript - 需要 HTML 框架的替代品(我现在知道它们为什么是邪恶的了)

c# - C# 中的类无法识别 System.Drawing 中的图像类

对 sharepoint 的 C# CAML 查询返回列表中的所有项目(而不是仅匹配查询值的项目)

c# - 线程停止得不够快

c# - WPFToolkit 数据网格 : Highlight modified rows

c# - 如何使用处理程序显示图像预览

c# - 使用来自 ADO.Net 的输入参数调用存储过程时出错

javascript - 如何使用用户脚本将框架添加到现有框架集?