WPF Explicitly Update Binding Source or Target

By Michael Detras

Usually, the binding source is updated when the binding target (control) loses focus or when the property changes. If we want to have more control on when the update happens, we can explicitly update the binding target or source through code.

In this example, we have a window containing two TextBox controls and one Button. On clicking the Button, the text in tbx1 will be sent to the binding source. This will trigger a SourceUpdated event, and the event handler will explicitly update the text in tbx2. To do this, we have to set the UpdateSourceTrigger of the binding in tbx1 to Explicit. We then use the BindingExpression class' UpdateSource and UpdateTarget methods.

<Window x:Class="WpfApplication1.MainWindow"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         
Title="MainWindow" SizeToContent="WidthAndHeight">
    <Grid>
        <StackPanel Orientation="Horizontal"
             
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">
            <TextBox x:Name="tbx1" Margin="4" Width="100" Text="{Binding SharedText, NotifyOnSourceUpdated=True, UpdateSourceTrigger=Explicit}" Binding.SourceUpdated="OnSourceUpdated"/>
            <TextBox x:Name="tbx2" Margin="4" Width="100" Text="{Binding SharedText}"/>
            <Button Content="Bind to Source" Margin="4" Click="OnBtnClick"/>
        </StackPanel>
    </Grid>
</Window>

public partial class MainWindow : Window
{
    public string SharedText { get; set; }

    public MainWindow()
    {
         InitializeComponent();
    }

     private void OnSourceUpdated(object sender, DataTransferEventArgs e)
    {
         var bindingExpression = tbx2.GetBindingExpression(TextBox.TextProperty);
        bindingExpression.UpdateTarget();
    }

    private void OnBtnClick(object sender, RoutedEventArgs e)
    {
         var bindingExpression = tbx1.GetBindingExpression(TextBox.TextProperty);
        bindingExpression.UpdateSource();
    }
}

Related FAQs

When using converters for data binding, we usually use the Convert method of an IValueConverter and just leave the ConvertBack method unimplemented. The ConvertBack method lets us update the binding source.
WPF Explicitly Update Binding Source or Target  (6136 Views)