在用户从显示的Page
中选择“是”之后,我试图导航到MessageBox
,但是我的Frame
不会导航,直到我显示另一个MessageBox
告诉用户导航已完成。
我尝试在“成功” Thread.Sleep(5000);
之后添加另一个MessageBox
和MessageBox
(以查看Frame
是否仅在整个方法完成后才更新),但是“成功” MessageBox
出现后,框架仍将导航。
这是我的MainWindow.xaml:
<Window x:Class="WpfApp23.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp23"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition />
</Grid.RowDefinitions>
<Frame x:Name="MyFrame" Content="" Margin="0" />
<Button x:Name="MyButton" Content="Navigate" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center" Width="75" Click="MyButton_Click" Grid.Row="1" />
</Grid>
</Window>
这是MainWindow.xaml.cs中的按钮单击事件处理程序:
private void MyButton_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult messageBoxResult = MessageBox.Show("Navigate to page?", "Test", MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
MyFrame.NavigationService.Navigate(new Uri("Test.xaml", UriKind.Relative));
Thread.Sleep(5000); // Used to exaggerate time it takes to do other tasks.
MessageBox.Show("Success");
}
}
Test.xaml
只是我创建的虚拟页面,除了标签外什么都没有:
<Grid>
<Label Content="Test Page" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center" />
</Grid>
我希望Frame
在用户选择“是”后立即进行导航,那么为什么要等待导航直到“成功” MessageBox
出现?
答案 0 :(得分:1)
您无法入睡,显示消息框并在同一线程上同时导航到页面。
如果要在浏览页面后显示MessageBox
,则可以处理Navigated
事件。
private void MyButton_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult messageBoxResult = MessageBox.Show("Navigate to page?", "Test", MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
System.Windows.Navigation.NavigatedEventHandler handler = null;
handler = async (ss, ee) =>
{
await Task.Delay(1000);
MessageBox.Show("Success");
MyFrame.Navigated -= handler;
};
MyFrame.Navigated += handler;
MyFrame.NavigationService.Navigate(new Uri("Test.xaml", UriKind.Relative));
}
}
答案 1 :(得分:-1)