-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathTextBoxLineCountBehavior.cs
More file actions
50 lines (44 loc) · 1.81 KB
/
TextBoxLineCountBehavior.cs
File metadata and controls
50 lines (44 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Threading;
using System.Windows.Threading;
using Microsoft.Xaml.Behaviors;
namespace MaterialDesignThemes.Wpf.Behaviors;
/// <summary>
/// Behavior exposing the <see cref="TextBox.LineCount"/> (non-DP) as attached properties which are bindable from XAML.
/// </summary>
public class TextBoxLineCountBehavior : Behavior<TextBox>
{
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 &&
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);
Interlocked.CompareExchange(ref _uiUpdateInProgress, 0, 1);
},
DispatcherPriority.Background);
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;
AssociatedObject.LayoutUpdated += AssociatedObjectOnLayoutUpdated;
}
protected override void OnDetaching()
{
if (AssociatedObject is { } associatedObject)
{
associatedObject.TextChanged -= AssociatedObjectOnTextChanged;
associatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated;
}
base.OnDetaching();
}
}