Handle Clipboard Paste in WPF

public YourWindow()
{
    InitializeComponent();

    // "yourTextBox" is your TextBox
    DataObject.AddPastingHandler(yourTextBox, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
    if (!isText) return;

    var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
    // Manipulate the text here
    text = text.Replace("oldValue", "newValue"); // Example manipulation

    // Set the new data
    e.DataObject = new DataObject(DataFormats.UnicodeText, text);
}

Note that this event is triggered after the user initiates the paste command but before the content is actually pasted into the TextBox, allowing you to modify or cancel the paste operation.

References
https://stackoverflow.com/questions/3061475/paste-event-in-a-wpf-textbox

Dependency Injection in WPF Application using Generic HostBuilder

Creating Generic HostBuilder

Nuget :

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.2

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

Initialize the Host

Within Constructor of App class(file: App.xaml.cs) please add below code to build Host,

host = new HostBuilder()
           .ConfigureServices((hostContext, services) =>
           {
 
           }).Build();

DI Container

host = new HostBuilder()
          .ConfigureServices((hostContext, services) =>
          {
              //Add business services as needed
              services.AddScoped<IEmployeeViewModel, EmployeeViewModel>();
 
              //Lets Create single tone instance of Master windows
              services.AddSingleton<EmployeeWindow>();
 
          }).Build();

Setting up OnStartup and OnExit Application events

private void OnStartup(object sender, StartupEventArgs e)
        {
            var mainWindow = host.Services.GetService<EmployeeWindow>();
            mainWindow.Show();
        }
protected override async void OnExit(ExitEventArgs e)
       {
           using (host)
           {
               await host.StopAsync();
           }
 
           base.OnExit(e);
       }

App.XAML file used as below,

<Application x:Class="WPFDesktopApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Startup="OnStartup">
    <Application.Resources>
         
    </Application.Resources>
</Application>

References
https://www.thecodebuzz.com/dependency-injection-wpf-generic-hostbuilder-net-core/
https://laurentkempe.com/2019/09/03/WPF-and-dotnet-Generic-Host-with-dotnet-Core-3-0/

Value conversion with IValueConverter in WPF

<Window x:Class="WpfTutorialSamples.DataBinding.ConverterSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTutorialSamples.DataBinding"
        Title="ConverterSample" Height="140" Width="250">
    <Window.Resources>
        <local:YesNoToBooleanConverter x:Key="YesNoToBooleanConverter" />
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBox Name="txtValue" />
        <WrapPanel Margin="0,10">
            <TextBlock Text="Current value is: " />
            <TextBlock Text="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}"></TextBlock>
        </WrapPanel>
        <CheckBox IsChecked="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}" Content="Yes" />
    </StackPanel>
</Window>
using System;
using System.Windows;
using System.Windows.Data;

namespace WpfTutorialSamples.DataBinding
{
    public partial class ConverterSample : Window
    {
        public ConverterSample()
        {
            InitializeComponent();
        }
    }

    public class YesNoToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch(value.ToString().ToLower())
            {
                case "yes":
                case "oui":
                    return true;
                case "no":
                case "non":
                    return false;
            }
            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if(value is bool)
            {
                if((bool)value == true)
                    return "yes";
                else
                    return "no";
            }
            return "no";
        }
    }
}

References
https://wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

Debug data bindings in WPF using Converter

<Window x:Class="WpfTutorialSamples.DataBinding.DataBindingDebuggingSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:self="clr-namespace:WpfTutorialSamples.DataBinding"
        Title="DataBindingDebuggingSample" Name="wnd" Height="100" Width="200">
    <Window.Resources>
        <self:DebugDummyConverter x:Key="DebugDummyConverter" />
    </Window.Resources>
    <Grid Margin="10">
        <TextBlock Text="{Binding Title, ElementName=wnd, Converter={StaticResource DebugDummyConverter}}" />
    </Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Data;
using System.Diagnostics;

namespace WpfTutorialSamples.DataBinding
{
    public partial class DataBindingDebuggingSample : Window
    {
        public DataBindingDebuggingSample()
        {
            InitializeComponent();
        }
    }

    public class DebugDummyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Debugger.Break();
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Debugger.Break();
            return value;
        }
    }
}

References
https://wpf-tutorial.com/data-binding/debugging/

Handle and raising events in C#

Events

class Counter
{
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        EventHandler handler = ThresholdReached;
        handler?.Invoke(this, e);
    }

    // provide remaining implementation for the class
}

Event data

public class ThresholdReachedEventArgs : EventArgs
{
    public int Threshold { get; set; }
    public DateTime TimeReached { get; set; }
}

Event handlers

class Program
{
    static void Main()
    {
        var c = new Counter();
        c.ThresholdReached += c_ThresholdReached;

        // provide remaining implementation for the class
    }

    static void c_ThresholdReached(object sender, EventArgs e)
    {
        Console.WriteLine("The threshold was reached.");
    }
}

References
https://docs.microsoft.com/en-us/dotnet/standard/events/
https://www.tutorialsteacher.com/csharp/csharp-event