# Navigate between views

Version: 0.5.0
Framework commit: d503df2befa756e681fcdc6250e9552dc7388bea
Canonical URL: /docs/0.5.0/guides/navigation/

A navigation model owns where the application is and how users return. Separate that model from the presentation of a navigation bar, tabs, or a side pane.


## Start with two tabs

For a small settings screen, the control can own the selection without a route service:

```xml
<TabControl xmlns="https://github.com/ferroui">
  <TabItem Header="General">
    <StackPanel Margin="16" Spacing="8">
      <TextBlock Text="General settings" />
      <CheckBox Content="Show tips at startup" />
    </StackPanel>
  </TabItem>
  <TabItem Header="Account">
    <TextBlock Margin="16" Text="Account settings" />
  </TabItem>
</TabControl>
```

Switch tabs with both pointer and keyboard. Move each page into a reusable `UserControl` as it grows. If a destination needs a record ID, browser URL, or back stack, introduce an explicit navigation model rather than treating tab positions as routes.

## Choose the model

Use a small content host when the application has a few independent views. Use `Frame` and page navigation for a stack/history workflow. Use a NavigationView when the shell needs a top-level navigation structure. Declarative applications use the router of `ferroui-view`; MVVM applications use the routing state of ReactiveUI.

A navigation control's selection is not automatically your application's route. Synchronize them deliberately, including back navigation and programmatic changes.

## Own view state deliberately

Decide whether returning to a page recreates it or restores an existing view model. A details page may need a stable record identifier rather than a reference to a particular control instance. Keep persisted application state out of transient view objects.

## Browser considerations

The browser has its own history and URL. If users must bookmark a location, map routes to that URL explicitly. A native page stack alone does not establish a browser deep-link contract.

## Lifetimes and cleanup

Cancel obsolete loads, release subscriptions, and stop timers when leaving a view. If views are intentionally cached, distinguish being retained from being active. A cached view should not continue expensive work merely because an object still owns it.

Test forward, back, repeated navigation to the same destination, missing records, and errors during asynchronous page loading.

## Route between components

In declarative Rust, `router(initial, routes)` shows the view of the first matching route and gives the components below a `Router` handle:

```rust
use ferroui_view::prelude::*;

#[component(rerender)]
fn Shell() -> Element {
    let routes = vec![
        route("/", |_| rsx! { Home {} }),
        route("/people/:id", |m| rsx! { Person { id: m.param("id").unwrap_or_default().to_string() } }),
        route("*", |m| rsx! { NotFound { path: m.path().to_string() } }),
    ];
    rsx! { Grid { {router("/", routes)} } }
}

#[component(rerender)]
fn Home() -> Element {
    let router = use_router();
    rsx! { Button { on_click: move |_| router.navigate("/people/42"), "Open person 42" } }
}
```

`Home`, `Person`, and `NotFound` are the application's components. The stack holds paths, so a details page receives a record identifier, not a control. `navigate_back`, `navigate_and_reset`, `can_go_back`, and `current` complete the handle; [lists, async data & routing](/docs/0.5.0/declarative/patterns/) describes the patterns. Another route mounts its view anew and removes the previous view with its state, so state that outlives navigation lives above the router.

## Connect a routed view model

ReactiveUI applications can let a screen own `RoutingState` and host its current page with this view fragment:

```xml
<rxui:RoutedViewHost xmlns="https://github.com/ferroui"
                    xmlns:rxui="using:ReactiveUI.FerroUI"
                    Router="{ReflectionBinding Router}">
  <rxui:RoutedViewHost.DefaultContent>
    <TextBlock Text="Select a page to begin." />
  </rxui:RoutedViewHost.DefaultContent>
</rxui:RoutedViewHost>
```

Initialize ReactiveUI, register its markup types and your view mappings, and expose `Router` on the screen's data context. `navigate`, `navigate_and_reset`, and `navigate_back` are commands; subscribe to the returned execution observable to execute them. See the complete [screen view model](https://github.com/wieslawsoltes/FerroUI/blob/d503df2befa756e681fcdc6250e9552dc7388bea/samples/ReactiveUIExample/ViewModels/main_view_model.rs) for construction and routing errors.

## Try the controls


Switch between the views with pointer and keyboard. This example demonstrates local tab selection without a route service.

### Related views

```xml
<TabControl xmlns="https://github.com/ferroui">
  <TabItem Header="Overview"><TextBlock Margin="16" Text="The big picture." /></TabItem>
  <TabItem Header="Details"><TextBlock Margin="16" Text="A closer look." /></TabItem>
</TabControl>
```

```rust
use ferroui::prelude::*;
use ferroui::base::metadata::from_markup_value;
use ferroui::markup_xaml_loader::FerroRuntimeXamlLoader;

#[repr(C)]
pub struct App {
    base: Application,
}

ferro_class!(App: Application);
ferro_impl_classes!(App: FerroObjectImpl);

impl NewApplication for App {
    fn new_application() -> Ref<Self> {
        instantiate(Self { base: Application::construct() })
    }
}

impl ApplicationImpl for App {
    fn initialize(this: &Self) {
        Self::parent_initialize(this);
        ferroui::controls::register_types();
        FerroRuntimeXamlLoader::register();
        this.styles().add(FluentTheme::new().as_style());
    }

    fn on_framework_initialization_completed(this: &Self) {
        let lifetime = this.application_lifetime();
        if let Some(desktop) = lifetime.as_ref().and_then(|l| l.as_classic_desktop_style_application_lifetime()) {
            let value = FerroRuntimeXamlLoader::load(include_str!("View.xaml"), None, None, None, false)
                .expect("Example XAML should load");
            let view = from_markup_value::<Ref<Control>>(&Some(value)).expect("Example root must be a control");
            let window = Window::new();
            window.set_title(Some("FerroUI documentation example".to_owned()));
            window.set_width(560.0);
            window.set_height(420.0);
            window.set_padding(Thickness::uniform(24.0));
            window.set_content(Some(Control::boxed(view)));
            desktop.set_main_window(Some(window));
        }
        Self::parent_on_framework_initialization_completed(this);
    }
}

fn main() -> std::process::ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = AppBuilder::configure::<App>().use_platform_detect().start_with_classic_desktop_lifetime(&args);
    std::process::ExitCode::from(result as u8)
}

```

[Download the complete desktop project](/docs/0.5.0/generated/examples/tabs.zip). The browser preview runs real FerroUI controls with precompiled Rust support; this desktop application loads the same XAML.


## Public APIs and controls

- [TabControl](/docs/0.5.0/controls/reference/tabcontrol/), [Frame](/docs/0.5.0/controls/reference/frame/), and [NavigationView](/docs/0.5.0/controls/reference/navigationview/) — choose a navigation presentation.
- [`router`](/docs/0.5.0/api/ferroui-view/router/function-router/), [`route`](/docs/0.5.0/api/ferroui-view/router/function-route/), and [`use_router`](/docs/0.5.0/api/ferroui-view/router/function-use_router/) — routed components.
- [`RoutingState`](/docs/0.5.0/api/ferroui-reactiveui/routing/struct-routingstate/) and [`RoutedViewHost`](/docs/0.5.0/api/ferroui-reactiveui-controls/struct-routedviewhost/) — routed MVVM screens.
- [`ViewModelViewHost`](/docs/0.5.0/api/ferroui-reactiveui-controls/struct-viewmodelviewhost/) — locate a view for a model without a navigation stack.
