参考地址:https://www.cnblogs.com/Jaasdsa/p/6164200.html
这篇文章中,最后一个方法,利用反射来使得每个子页面都能访问主页面的介绍中,所给出的代码运行会失败,提示非静态方法需要一个目标。
下面给出的程序已经对此进行了修复。可以正常运行。
前台:
后台:
namespace WPFClient.App
{/// /// MainWindow.xaml 的交互逻辑/// public partial class MainWindow : Window{public MainWindow(){InitializeComponent();Navigate("Home");}#region 页面导航private void btnNav_Click(object sender, RoutedEventArgs e){Button btn = sender as Button;Navigate(btn.Tag.ToString());}private void Navigate(string path){string uri = "WPFClient.App.Views." + path;Type type = Type.GetType(uri);if (type != null){//实例化Page页// object obj = type.Assembly.CreateInstance(uri);object obj = Activator.CreateInstance(type);Page control = obj as Page;this.frmMain.Content = control;PropertyInfo[] infos = type.GetProperties();foreach (PropertyInfo info in infos){//将MainWindow设为page页的ParentWinif (info.Name == "ParentWindow"){info.SetValue(control, this, null);break;}}}}#endregion//公共方法public void CallFromChild(string name){MessageBox.Show("Hello," + name + "!");}}
}
创建一个类:
namespace WPFClient.App
{public class BasePage : Page{#region 父窗体private MainWindow _parentWin;public MainWindow ParentWindow{get { return _parentWin; }set { _parentWin = value; }}#endregion}
}
子页的前台
子页的后台
namespace WPFClient.App.Views
{/// /// Home.xaml 的交互逻辑/// public partial class Home : BasePage{public Home(){InitializeComponent();}private void btnCall_Click(object sender, RoutedEventArgs e){string param = txtParam.Text;ParentWindow.CallFromChild(param);}}
}
这种方案使得Page页访问MainWindow中的公共属性、控件元素或公共变量也是可行的。
此外将BasePage的基类从Page改成UserControl也是可以的