diff --git a/src/MaterialDesignThemes.Wpf/Behaviors/TextBoxLineCountBehavior.cs b/src/MaterialDesignThemes.Wpf/Behaviors/TextBoxLineCountBehavior.cs index 2df10c85a3..5caecb2d65 100644 --- a/src/MaterialDesignThemes.Wpf/Behaviors/TextBoxLineCountBehavior.cs +++ b/src/MaterialDesignThemes.Wpf/Behaviors/TextBoxLineCountBehavior.cs @@ -1,4 +1,5 @@ -using System.Windows.Threading; +using System.Threading; +using System.Windows.Threading; using Microsoft.Xaml.Behaviors; namespace MaterialDesignThemes.Wpf.Behaviors; @@ -11,18 +12,22 @@ public class TextBoxLineCountBehavior : Behavior private void AssociatedObjectOnTextChanged(object sender, TextChangedEventArgs e) => UpdateAttachedProperties(); private void AssociatedObjectOnLayoutUpdated(object? sender, EventArgs e) => UpdateAttachedProperties(); + private int _uiUpdateInProgress = 0; + private void UpdateAttachedProperties() { - if (AssociatedObject is { } associatedObject) + if (AssociatedObject is { } associatedObject && + Interlocked.CompareExchange(ref _uiUpdateInProgress, 1, 0) == 0) { associatedObject.Dispatcher - .BeginInvoke(() => - { - int lineCount = associatedObject.LineCount; - associatedObject.SetCurrentValue(TextFieldAssist.TextBoxLineCountProperty, lineCount); - associatedObject.SetCurrentValue(TextFieldAssist.TextBoxIsMultiLineProperty, lineCount > 1); - }, - DispatcherPriority.Background); + .BeginInvoke(() => + { + int lineCount = associatedObject.LineCount; + associatedObject.SetCurrentValue(TextFieldAssist.TextBoxLineCountProperty, lineCount); + associatedObject.SetCurrentValue(TextFieldAssist.TextBoxIsMultiLineProperty, lineCount > 1); + Interlocked.CompareExchange(ref _uiUpdateInProgress, 0, 1); + }, + DispatcherPriority.Background); } } @@ -35,10 +40,10 @@ protected override void OnAttached() protected override void OnDetaching() { - if (AssociatedObject != null) + if (AssociatedObject is { } associatedObject) { - AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged; - AssociatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated; + associatedObject.TextChanged -= AssociatedObjectOnTextChanged; + associatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated; } base.OnDetaching(); }