# Bind controls to application state

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

A control property can follow application state in two ways. In declarative Rust, a property follows a signal, a memo, or a closure directly, and a two-way value writes edits back. In XAML, and from Rust through the property system, a binding connects a target property to a value on a source object, usually the current `DataContext`; the source must expose the properties and notifications FerroUI's binding system expects.

## Follow a signal in declarative Rust

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

#[component]
pub fn Search() -> Element {
    let search_text = signal(String::new());
    rsx! {
        StackPanel { spacing: 12.0,
            TextBox { text: search_text.two_way(), placeholder_text: "Search" }
            TextBlock { text: search_text }
            TextBlock { text: move || format!("{} characters", search_text.with(|text| text.chars().count())) }
        }
    }
}
```

Typing writes into `search_text`; both text blocks follow it, and nothing else runs. There is no notification to raise and no name to register: the signal is the source, and the compiler checks the property names and value types. A closure recalculates when the signals it reads change. In a component that runs again, `text: format!(..)` with a value read in the function also works: the component runs and the reconciler sets the new text.

To bind an element to a view model instead, `.bind(property, binding)` sets a binding of the property system on any element, and `use_data_context` reads the data context in a component ([components with XAML](/docs/0.5.0/declarative/xaml-interop/)).

## Bind to a view model in XAML

```xml
<StackPanel xmlns="https://github.com/ferroui" Spacing="12">
  <TextBox Text="{ReflectionBinding SearchText, Mode=TwoWay}" />
  <TextBlock Text="{ReflectionBinding SearchText}" />
</StackPanel>
```


## Try a binding

This example binds to another named control rather than a view model. Edit the text field in the running preview: the label follows the same public Text property and notification system used by view-model bindings.

### A binding that updates as you type

```xml
<StackPanel xmlns="https://github.com/ferroui"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Spacing="12">
  <TextBlock Text="Edit the field to update the label" />
  <TextBox x:Name="Editor" Text="Hello, FerroUI" />
  <TextBlock x:Name="Echo" Text="{Binding Text, ElementName=Editor}" FontSize="20" />
</StackPanel>
```

```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/element-binding.zip). The browser preview runs real FerroUI controls with precompiled Rust support; this desktop application loads the same XAML.


## Pick the binding direction

Use one-way binding for values the UI only displays. Use two-way binding when a control edits view-model state. A default binding mode can be property-specific; write `Mode=TwoWay` explicitly while learning or debugging a form.

A value changing in memory does not automatically update the UI. The source must notify the binding system. With ReactiveUI, use the reactive property macros or the corresponding change-notification APIs. See [MVVM](/docs/0.5.0/guides/mvvm/).

## Source paths and names

Binding paths use the markup-facing property names from registration. Rust's `search_text` field convention does not imply that `SearchText` is registered automatically. A reactive property's declared notification name and its markup metadata must agree.

Use an explicit source or named-control binding when the value belongs to another control rather than the view model. Avoid replacing a container's data context just to bind one child: doing so changes every descendant binding that inherits that context.

## Compiled and runtime bindings

Build-time markup compiles binding paths by default and needs source type information. The untyped examples above choose `ReflectionBinding` explicitly. See [compiled binding setup](/docs/0.5.0/xaml/compilation/#migrate-to-compiled-bindings-by-default) for the typed form and runtime loader configuration. If a path works in an imperative Rust call but not in XAML, check registration, source type, property name, and notification behavior.

## Diagnose a binding

1. Confirm that the control has the intended `DataContext`.
2. Inspect the binding path and its markup-facing names.
3. Confirm that the source exposes a getter and, when editing, a setter.
4. Change the source and verify a notification is raised.
5. Check the developer tools for the target's effective value and value source.

Use converters for presentation transformations. Keep business validation and domain decisions in the model or view model so they remain testable without a UI.

## Choose the source intentionally

| Example | Source | Use it when |
| --- | --- | --- |
| `{ReflectionBinding SearchText}` | Inherited data context | The value belongs to the view model |
| `{ReflectionBinding SearchText, Mode=TwoWay}` | Writable data-context property | The user edits model state |
| `{Binding #Query.Text}` | Named control `Query` | One view element follows another |

For a model binding, start by setting the property in Rust and confirming the view updates; then edit the control and confirm the setter runs. This separates missing notifications from a missing two-way path. See [forms](/docs/0.5.0/guides/forms/) for the full input, validation, and submit contract.

## Public APIs and controls

- [`signal`](/docs/0.5.0/api/ferroui-view/reactive/function-signal/), [`Signal`](/docs/0.5.0/api/ferroui-view/reactive/struct-signal/), and [`TwoWay`](/docs/0.5.0/api/ferroui-view/reactive/struct-twoway/) — declarative state and two-way values.
- [`Binding`](/docs/0.5.0/api/ferroui-markup/data/struct-binding/) and [`BindingMode`](/docs/0.5.0/api/ferroui-base/data/enum-bindingmode/) — paths and update direction.
- [`ReactiveObject`](/docs/0.5.0/api/ferroui-reactiveui/reactive_object/struct-reactiveobject/) — notifying source state.
- [TextBox](/docs/0.5.0/controls/reference/textbox/) and [TextBlock](/docs/0.5.0/controls/reference/textblock/) — the editable and display targets in this guide.
