Files
Artemis/src/Avalonia/Artemis.UI.Shared/Behaviors/LostFocusTextBoxBindingBehavior.cs
T
Robert 2ae1f5f56c Node editor - Added node creation by dropping cables in empty space
Node editor - Added undo/redo to static value nodes
UI - Throw exception when binding a non-reactive view to an activatable view model
2022-03-26 19:13:51 +01:00

56 lines
1.5 KiB
C#

using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Artemis.UI.Shared.Behaviors;
/// <summary>
/// Represents a behavior that can be used to make a text box only update it's binding on focus loss.
/// </summary>
public class LostFocusTextBoxBindingBehavior : Behavior<TextBox>
{
public static readonly StyledProperty<string> TextProperty = AvaloniaProperty.Register<LostFocusTextBoxBindingBehavior, string>(
"Text", defaultBindingMode: BindingMode.TwoWay);
static LostFocusTextBoxBindingBehavior()
{
TextProperty.Changed.Subscribe(e => ((LostFocusTextBoxBindingBehavior) e.Sender).OnBindingValueChanged());
}
public string Text
{
get => GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
/// <inheritdoc />
protected override void OnAttached()
{
if (AssociatedObject != null)
AssociatedObject.LostFocus += OnLostFocus;
base.OnAttached();
}
/// <inheritdoc />
protected override void OnDetaching()
{
if (AssociatedObject != null)
AssociatedObject.LostFocus -= OnLostFocus;
base.OnDetaching();
}
private void OnLostFocus(object? sender, RoutedEventArgs e)
{
if (AssociatedObject != null)
Text = AssociatedObject.Text;
}
private void OnBindingValueChanged()
{
if (AssociatedObject != null)
AssociatedObject.Text = Text;
}
}