[英]Refresh function when navigated to a page again in wpf
In my wpf app I have two pages, page1
and page2
. 在我的wpf应用程序中,我有两个页面,
page1
和page2
。
when the user go from page1
to page2
in the first time it automatically creates a new page2
. 当用户第一次从
page1
转到page2
时,它会自动创建一个新的page2
。
in page1
it looks something like: 在第1
page1
,内容类似于:
public static int someVar;
public Page1()
{
InitializeComponent();
}
.
.
.
// the user gives some value to "someVar"
void Next_btn(object sender , RoutedEventArgs e)
{
if (this.NavigationService.CanGoForward)
this.NavigationService.GoForward();
else
NavigationService.Navigate(new Page2());
}
in page2
it looks like: 在
page2
它看起来像:
public Page2()
{
InitializeComponent();
if(Page1.someVar==3)
DoSomething();
}
.
.
.
void Back_btn(object sender , RoutedEventArgs e)
{
if (this.NavigationService.CanGoBack)
this.NavigationService.GoBack();
}
My problem is this: 我的问题是这样的:
let's say that the user done the following: 假设用户执行了以下操作:
the user have been in page1
and puts someVar=2
and then goes to page2
. 用户已经进入
page1
并someVar=2
,然后转到page2
。 therefore the function DoSomething()
wont be called. 因此,不会调用函数
DoSomething()
。 after that he went back to page1 and changed someVar=3
and then navigated again to page2 still the function DoSomething()
wont be called(But I need that it will be called it this scenario), because it's not a new page2
. 之后,他回到page1并更改了
someVar=3
,然后再次导航到page2,仍然不会调用函数DoSomething()
(但是在这种情况下我需要将其称为),因为它不是新的 page2
。
how to solve the following scenario without navigate to a new page2
every time? 如何解决以下情况而无需每次都导航到新的
page2
?
The code in the constructor will only be executed once for each instance of Page2. 构造函数中的代码将仅针对Page2的每个实例执行一次。
But you could handle the Navigated
event for the NavigationService
in Page1
and call the DoSomething()
method of Page2
in the event handler. 但是您可以在
Page1
处理NavigationService
的Navigated
事件,并在事件处理程序中调用Page2
的DoSomething()
方法。 Something like this: 像这样:
void Next_btn(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigated += NavigationService_Navigated;
if (this.NavigationService.CanGoForward)
this.NavigationService.GoForward();
else
NavigationService.Navigate(new Page2());
}
private void NavigationService_Navigated(object sender, NavigationEventArgs e)
{
var page2 = NavigationService.Content as Page2;
if (page2 != null && someVar == 3)
page2.DoSomething();
this.NavigationService.Navigated -= NavigationService_Navigated;
}
Thanks to @8mm
for his guidance, the following code worked for me: 感谢
@8mm
的指导,以下代码对我有用:
Page2 p2=new Page2();
void Next_btn(object sender , RoutedEventArgs e)
{
if (this.NavigationService.CanGoForward)
{
p2.DoSomething();
this.NavigationService.GoForward();
} else
NavigationService.Navigate(p2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.