Using a Button to navigate to another Page in a NavigationWindow

我是研究僧i 提交于 2019-12-03 14:32:45

According to the documentation, only DocumentViewer and FlowDocumentViewer implement this command specifically. You'll need to either find a command for navigation that NavigationWindow implements, or set up a CommandBinding for this command and handle it yourself.

In XAML:

<Button Command="{x:Static Views:Commands.NavigateHelp}" Content="Help"/>

In Views (We have a Commands.cs file that contains all of these):

public static RoutedCommand NavigateHelp = new RoutedCommand();

In the Page contstructor, you can connect the two:

CommandBindings.Add(new CommandBinding(Commands.NavigateHelp, NavigateHelpExecute));

NavigateHelpExecute can be in the code behind (which is what we do), hook into a ViewModel event handler, or whatever. The beauty of this is that you can disable other navigation like so:

CommandBindings.Add(new CommandBinding(NavigationCommands.Refresh, null));

Hope this helps.

You will want to use the NavigationService of your NavigationWindow as follows:

XAML:

    <Button HorizontalAlignment="Right" Name="continueButton" Width="75" Margin="0,0,8,11" Height="23" VerticalAlignment="Bottom" Click="continueButton_Click">
        Continue
    </Button>

C#:

    private void continueButton_Click(object sender, RoutedEventArgs e)
    {
        this.NavigationService.GoForward();
        //or
        this.NavigationService.Navigate("Second.xaml")
    }

With either of this you can use use this, I only show the NavigationService here for clarity

public class NavigateButton : Button
{
    public Uri NavigateUri { get; set; }

    public NavigateButton()
    {
        Click += NavigateButton_Click;
    }

    void NavigateButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        var navigationService = NavigationService.GetNavigationService(this);
        if (navigationService != null)
            navigationService.Navigate(NavigateUri);
    }
}

And then you can put the following in your xaml:

<local:NavigateButton Content="NavigateButton" NavigateUri="Page2.xaml"/>

Then you still don't need code behind your pages, and you don't need to add commands to your viewmodel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!