forked from MaterialDesignInXAML/MaterialDesignInXamlToolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextBoxLineCountBehavior.cs
More file actions
45 lines (40 loc) · 1.61 KB
/
TextBoxLineCountBehavior.cs
File metadata and controls
45 lines (40 loc) · 1.61 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
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 void UpdateAttachedProperties()
{
if (AssociatedObject is { } associatedObject)
{
associatedObject.Dispatcher
.BeginInvoke(() =>
{
int lineCount = associatedObject.LineCount;
associatedObject.SetCurrentValue(TextFieldAssist.TextBoxLineCountProperty, lineCount);
associatedObject.SetCurrentValue(TextFieldAssist.TextBoxIsMultiLineProperty, lineCount > 1);
},
DispatcherPriority.Background);
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;
AssociatedObject.LayoutUpdated += AssociatedObjectOnLayoutUpdated;
}
protected override void OnDetaching()
{
if (AssociatedObject != null)
{
AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged;
AssociatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated;
}
base.OnDetaching();
}
}