In a previous post called WPF DataContext – Targeting the Main Window we saw that when we entered in the numbers for the new width or height dimensions, it was not updated immediately. It was only updated after we hit the Tab key and the text box lost the focus. This behavior is controlled by a property on the binding called UpdateSourceTrigger. It defaults to the value “Default“, which basically means that the source is updated based on the property that you bind to. The four possible values of the UpdateSourceTrigger property are:
- Default
- PropertyChanged
- LostFocus
- Explicit
An Example from WPF Tutorial
This example that follows is based on an article by WPF Tutorial called Data binding: The UpdateSourceTrigger property.
<Window x:Class="UpdateSourceTrigger.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:UpdateSourceTrigger" mc:Ignorable="d" Topmost="False" WindowStartupLocation="CenterScreen" Title="UpdateSourceTrigger" Height="250" Width="400" MinWidth="200"> <StackPanel Margin="15"> <WrapPanel> <TextBlock Text="Window title: " /> <TextBox Name="txtWindowTitle" Text="{Binding Title, UpdateSourceTrigger=Explicit}" Width="150" /> <Button Name="btnUpdateSource" Click="btnUpdateSource_Click" Margin="5,0" Padding="5,0">*</Button> </WrapPanel> <WrapPanel Margin="0,10,0,0"> <TextBlock Text="Window dimensions (w x h): " /> <TextBox Text="{Binding Width, UpdateSourceTrigger=LostFocus}" Width="50" /> <TextBlock Text=" x " /> <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged}" Width="50" /> </WrapPanel> </StackPanel> </Window>
Below is the C# code.
using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace UpdateSourceTrigger { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = this; } private void btnUpdateSource_Click(object sender, RoutedEventArgs e) { BindingExpression binding = txtWindowTitle.GetBindingExpression(TextBox.TextProperty); binding.UpdateSource(); } } }