XAML
01 / 02

XAML: Data Binding, Resources & MVVM

XAML: Data Binding, Resources & MVVM

Data Binding & INotifyPropertyChanged

<!-- Connects the UI to a data source, instead of a fixed literal --
     the UI updates automatically when the underlying data changes -->
<TextBlock Text="{Binding UserName}" />

<!-- Mode=TwoWay: typing in the box also updates the ViewModel back -->
<TextBox Text="{Binding UserName, Mode=TwoWay}" />
public class UserViewModel : INotifyPropertyChanged
{
    private string _userName;

    public string UserName
    {
        get => _userName;
        set
        {
            _userName = value;
            // Fires the notification that triggers the bound TextBlock
            // to automatically refresh its displayed text
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(UserName)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Resources & Styles

<Window.Resources>
  <SolidColorBrush x:Key="PrimaryBrush" Color="#2563EB" />

  <!-- Style centralizes shared property values instead of repeating
       them on every matching element -->
  <Style x:Key="HeaderText" TargetType="TextBlock">
    <Setter Property="FontSize" Value="24" />
    <Setter Property="FontWeight" Value="Bold" />
  </Style>
</Window.Resources>

<TextBlock Style="{StaticResource HeaderText}" Text="Dashboard" />
<Button Background="{StaticResource PrimaryBrush}" Content="Save" />

DataTemplate for List Items

<ListBox ItemsSource="{Binding Users}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <Image Source="{Binding AvatarUrl}" Width="32" />
        <TextBlock Text="{Binding Name}" Margin="8,0,0,0" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Converters & MVVM's Testability Benefit

<!-- IValueConverter transforms a source value into the type/format
     the target property actually expects -->
<TextBlock Visibility="{Binding IsError, Converter={StaticResource BoolToVisibilityConverter}}" />

A ViewModel with no direct reference to actual UI element instances -- communicating with the View purely through data binding -- can be unit-tested in isolation, without instantiating any real controls. This separation of concerns is a core benefit of the MVVM pattern commonly used with XAML-based frameworks.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free