Skip to main content

WPF C#/VB
Boost Performance with Data Binding

C#

// AZUL CODING ---------------------------------------
// WPF C#/VB - Boost Performance with Data Binding
// https://youtu.be/7OZYJbrZ0ds


using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Documents;

namespace DataBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ObservableCollection<Person> PersonData = new();

        public MainWindow()
        {
            InitializeComponent();


            // Part 1
            Binding binding = new("Text")
            {
                Source = DataTxt
            };

            DataLbl.SetBinding(Run.TextProperty, binding);


            // Part 3
            PersonData.Add(new Person()
            {
                Name = "John Doe",
                Email = "johndoe@example.com",
                Phone = "123-456-7890"
            });

            PersonData.Add(new Person()
            {
                Name = "Jane Smith",
                Email = "janesmith@example.com",
                Phone = "098-765-4321"
            });

            DataTable.ItemsSource = PersonData;
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            if (DataTable.SelectedItem != null && !string.IsNullOrEmpty(EditTxt.Text))
                ((Person)DataTable.SelectedItem).Name = EditTxt.Text;
        }

        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (DataTable.SelectedItem != null)
                PersonData.Remove((Person)DataTable.SelectedItem);
        }
    }

    public class LinkTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString()?.StartsWith("https://") ?? false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool v)
            {
                if (v == true)
                    return "https://";
                else
                    return "";
            }
            return "";
        }
    }

    public class Person : INotifyPropertyChanged
    {
        private string name = "";
        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        public string Email { get; set; } = "";

        public string Phone { get; set; } = "";

        public event PropertyChangedEventHandler? PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
}

Enjoying this tutorial?


VB.NET

' AZUL CODING ---------------------------------------
' WPF C#/VB - Boost Performance with Data Binding
' https://youtu.be/7OZYJbrZ0ds


Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Globalization

Class MainWindow
    Private ReadOnly PersonData As New ObservableCollection(Of Person)

    Public Sub New()
        InitializeComponent()


        ' Part 1
        Dim binding As New Binding("Text") With {
            .Source = DataTxt
        }

        DataLbl.SetBinding(Run.TextProperty, binding)


        ' Part 3
        PersonData.Add(New Person With {
            .Name = "John Doe",
            .Email = "johndoe@example.com",
            .Phone = "123-456-7890"
        })

        PersonData.Add(New Person With {
            .Name = "Jane Smith",
            .Email = "janesmith@example.com",
            .Phone = "098-765-4321"
        })

        DataTable.ItemsSource = PersonData

    End Sub

    Private Sub EditBtn_Click(sender As Object, e As RoutedEventArgs)
        If DataTable.SelectedItem IsNot Nothing AndAlso Not String.IsNullOrEmpty(EditTxt.Text) Then
            DataTable.SelectedItem.Name = EditTxt.Text
        End If
    End Sub

    Private Sub DeleteBtn_Click(sender As Object, e As RoutedEventArgs)
        If DataTable.SelectedItem IsNot Nothing Then
            PersonData.Remove(DataTable.SelectedItem)
        End If
    End Sub
End Class

Public Class LinkTextConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
        Return value.ToString().StartsWith("https://") Or False
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        If TypeOf value Is Boolean Then
            If value Then
                Return "https://"
            Else
                Return ""
            End If
        End If
        Return ""
    End Function

End Class

Public Class Person
    Implements INotifyPropertyChanged

    Private _name As String = ""

    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            If _name <> value Then
                _name = value
                NotifyPropertyChanged("Name")
            End If
        End Set
    End Property

    Public Property Email As String = ""
    Public Property Phone As String = ""

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Sub NotifyPropertyChanged(propName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
    End Sub

End Class

XAML

<!-- AZUL CODING --------------------------------------- -->
<!-- WPF C#/VB - Boost Performance with Data Binding -->
<!-- https://youtu.be/7OZYJbrZ0ds -->


<Window x:Class="DataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataBinding"
        xmlns:system="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d" x:Name="Main"
        Title="Azul Coding - Data Binding" Width="400" SizeToContent="Height" ResizeMode="CanMinimize">
    <Window.Resources>
        <local:LinkTextConverter x:Key="LinkTextConverter" />
    </Window.Resources>
    <StackPanel Background="White">
        <Label x:Name="TitleLbl" Content="Data binding" Padding="5,0,5,5" Margin="20" FontWeight="SemiBold" FontSize="16" BorderBrush="DodgerBlue" BorderThickness="0,0,0,2"/>

        <!-- Part 1 -->
        <TextBox x:Name="DataTxt" TextWrapping="Wrap" Margin="20,0" FontSize="14" Padding="5"/>
        <TextBlock Margin="25,5,20,20" FontSize="14">
        <Run Text="You entered:"/>
        <Run x:Name="DataLbl" FontWeight="SemiBold" Text="{Binding Path=Text, ElementName=DataTxt}"/>
        </TextBlock>


        <!-- Part 2 -->
        <TextBlock Margin="25,0,20,0" FontSize="14" Text="{Binding ElementName=Main, Path=ActualWidth, StringFormat='The width of this window is {0:#,#.0}'}" />
        <TextBlock Margin="25,5,20,0" FontSize="14" Text="{Binding ElementName=Main, Path=ActualHeight, ConverterCulture='fr-FR', StringFormat='This app costs {0:C}'}" />
        <TextBlock Margin="25,5,20,20" FontSize="14" Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat='{}{0:HH:mm}'}" />

        <TextBox x:Name="LinkTxt" TextWrapping="Wrap" Margin="20,0" FontSize="14" Padding="5"/>
        <CheckBox x:Name="WebLinkCheck" Content="Web link?" IsChecked="{Binding ElementName=LinkTxt, Path=Text, Converter={StaticResource LinkTextConverter}}" FontSize="14" VerticalContentAlignment="Center" Margin="25,5,20,20"/>


        <!-- Part 3 -->
        <DataGrid x:Name="DataTable" Margin="20,0,20,10" IsReadOnly="True"/>
        <DockPanel Margin="20,0,20,20">
            <Button Name="DeleteBtn" DockPanel.Dock="Right" Padding="8,5" Margin="10,0,0,0" ToolTip="Delete" Background="#f0f0f0" Click="DeleteBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/delete-forever.png"/>
                </StackPanel>
            </Button>
            <Button Name="EditBtn" DockPanel.Dock="Right" Padding="10,5" Margin="10,0,0,0" Background="#f0f0f0" Click="EditBtn_Click">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                    <Image Height="24" Width="24" Source="https://img.icons8.com/fluency/48/edit.png"/>
                    <TextBlock Text="Edit name" VerticalAlignment="Center" FontSize="14" Margin="10,0,5,2"/>
                </StackPanel>
            </Button>
            <TextBox x:Name="EditTxt" TextWrapping="Wrap" FontSize="14" Padding="5" VerticalAlignment="Center"/>
        </DockPanel>
        
    </StackPanel>
</Window>