syn*_*rgy 6 c# string wpf xaml binding
我试图在页面之间传递一个简单的字符串,但我不知道如何。
我创建了一个测试应用程序,在其中单击一个按钮,“a”的值将传递到下一页(Page1.xaml.cs)
private void button1_Click(object sender, RoutedEventArgs e)
{
string a = "hello";
Page2 p2 = new Page2();
NavigationService.Navigate(p2, a);
}
Run Code Online (Sandbox Code Playgroud)
现在,我想从 Page1 (Page2.xaml.cs) 中提取数据
private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
string str = (string)e.ExtraData;
}
Run Code Online (Sandbox Code Playgroud)
然后在构造函数中订阅(Page2.xaml.cs)
public Page2()
{
InitializeComponent();
NavigationService.LoadCompleted += NavigationService_LoadCompleted;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行该程序时,出现错误。有人可以指出我错过了什么吗?
ViV*_*iVi -1
不要设置文本框 DataContext,而是将整个 page\xe2\x80\x99s datacontext 设置为某个类,即 page1 的 ViewModel。实现接口INotifyPropertyChanged并确保在字符串属性集中,NotifyPropertyChanged(\xe2\x80\x9cElementName\xe2\x80\x9d)引发
\n\n现在创建一个具有相应视图模型的新视图,如下所示,它还应该实现接口INotifyPropertyChanged。创建一个文本框并将其绑定到字符串属性,如第一页所示。确保双向绑定,以确保在数据更改时更新目标和源。
\n\n在 MainWindow 中创建两个 viewModel 的实例。当用户导航到第二个用户控件时,设置
\n\nPage2ViewModel.TextBoxString = Page1ViewModel.TextBoxString;\nRun Code Online (Sandbox Code Playgroud)\n\n从 Page2 导航到 Page1 时,反之亦然。
\n\nPage1ViewModel.TextBoxString = Page2ViewModel.TextBoxString;\nRun Code Online (Sandbox Code Playgroud)\n\n这样,两个文本框都将在导航过程中更新。\n这只是一个总体想法。您需要从一些教程中了解有关 MVVM 和 WPF 的更多信息。在谷歌搜索。
\n