Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Data Binding and UI Synchronization in WPF using INotifyPropertyChanged

Notes 1

XAML Ipmlementation

<Window x:Class="WpfDataBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Data Binding Demo" Height="150" Width="250">
    <Grid Margin="10">
        <StackPanel>
            <TextBox Text="{Binding DisplayText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
            <Button Content="Update Value" Click="UpdateValue_Click" Margin="0,10,0,0"/>
        </StackPanel>
    </Grid>
</Window>

C# Code-Behind and ViewModel

using System.ComponentModel;
using System.Windows;

namespace WpfDataBindingDemo
{
    public partial class MainWindow : Window
    {
        private readonly DataModel model = new DataModel();
        private int updateCount = 0;

        public MainWindow()
        {
            InitializeComponent();
            DataContext = model;
        }

        private void UpdateValue_Click(object sender, RoutedEventArgs e)
        {
            updateCount++;
            model.DisplayText = $"Update #{updateCount}";
        }
    }

    public class DataModel : INotifyPropertyChanged
    {
        private string _displayText = "Initial value";

        public string DisplayText
        {
            get => _displayText;
            set
            {
                _displayText = value;
                OnPropertyChanged(nameof(DisplayText));
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Tags: WPF

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.