From f1ba693f75fca70e7f41db83dff9074bc91e71fe Mon Sep 17 00:00:00 2001 From: Andreas Stenlund Date: Mon, 19 Oct 2020 18:13:05 +0200 Subject: [PATCH] Update IP address on both PropertyChanged and LostFocus --- Behaviors/UpdateSourceOnLostFocusBehavior.cs | 32 ++++++++++++++++++++ MainWindow.xaml | 7 +++-- 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 Behaviors/UpdateSourceOnLostFocusBehavior.cs diff --git a/Behaviors/UpdateSourceOnLostFocusBehavior.cs b/Behaviors/UpdateSourceOnLostFocusBehavior.cs new file mode 100644 index 0000000..efd66b6 --- /dev/null +++ b/Behaviors/UpdateSourceOnLostFocusBehavior.cs @@ -0,0 +1,32 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using Microsoft.Xaml.Behaviors; + +namespace fs2ff.Behaviors +{ + public class UpdateSourceOnLostFocusBehavior : Behavior + { + protected override void OnAttached() + { + base.OnAttached(); + + if (AssociatedObject != null) + AssociatedObject.LostFocus += AssociatedObject_LostFocus; + } + + protected override void OnDetaching() + { + if (AssociatedObject != null) + AssociatedObject.LostFocus -= AssociatedObject_LostFocus; + + base.OnDetaching(); + } + + private static void AssociatedObject_LostFocus(object sender, RoutedEventArgs e) + { + if (sender is TextBox textBox) + BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty)?.UpdateSource(); + } + } +} diff --git a/MainWindow.xaml b/MainWindow.xaml index 798e79f..7243944 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -5,7 +5,7 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.modernwpf.com/2019" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" - xmlns:behaviors="clr-namespace:fs2ff.Behaviors" + xmlns:b="clr-namespace:fs2ff.Behaviors" xmlns:c="clr-namespace:fs2ff.Converters" ui:WindowHelper.UseModernWindowStyle="True" mc:Ignorable="d" @@ -86,12 +86,13 @@ Text="{ Binding IpAddress, Mode=TwoWay, Converter={c:IpAddressToStringConverter}, - UpdateSourceTrigger=LostFocus}" + UpdateSourceTrigger=PropertyChanged, Delay=5000}" Template="{StaticResource WatermarkTextBoxTemplate}" Tag="255.255.255.255" Margin="0,10,0,0"> - + +