wpf.net-6.0caliburn.micro

NotifyOfPropertyChange Not updating in realtime


I have two Textboxes, I tried to update the second Textbox when i changed the first one but it's only work when i clicked another control or we can say a Button and also if i change the Second Textbox and click the button the First Textbox not gonna be updated.

I'm using WPF .Net 6.0

ShellView

<Window x:Class="WpfApp3.Views.ShellView"
    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:WpfApp3.Views"
    mc:Ignorable="d"
    Title="ShellView" Height="450" Width="450">
<Grid>
    <StackPanel>

        <TextBox Text="{Binding Path=Name , Mode=OneWay}"/>
        <TextBox x:Name="Name" />
        
        <Button Content="Click Me" />
        
    </StackPanel>

</Grid>

ShellViewModel

public class ShellViewModel : PropertyChangedBase
{
    string name = "";

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyOfPropertyChange(() => Name);
        }
    }
}

Recorded GIF


Solution

  • To synchronize both TextBox elements you must bind them to a common property using BindingMode.TwoWay (if both elements can update each other).

    To update the Binding set on the TextBox.Text property without moving the focus, you must configure the Binding accordingly by setting Binding.UpdateSourceTrigger to UpdateSourceTrigger.PropertyChanged. The default value is UpdateSourceTrigger.PropertyChanged. But TextBox internally changes this default to UpdateSourceTrigger.LostFocus to improve the performance and input handling for common scenarios. TextBox also sets the Binding.Mode of the TextBox.Text property to BindingMode.TwoWay which otherwise would default to BindingMode.OneWay.

    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
    <TextBox x:Name="Name" 
             Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
    

    If you e.g. trigger the operation that processes the text field's input with a button, I recommend to leave the UpdateSourceTrigger at the default.

    Microsoft Docs: Data binding overview (WPF .NET)