Skip to content

Instantly share code, notes, and snippets.

@jtheisen
Created January 11, 2014 23:39
Show Gist options
  • Save jtheisen/8378460 to your computer and use it in GitHub Desktop.
Save jtheisen/8378460 to your computer and use it in GitHub Desktop.
A behavior making a TextBox update the source on every key press.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace MonkeyBusters
{
// This behavior allows for TextBoxes which can't be tabbed away from - and would thus
// never update their source. They do update on key release now, which is not
// right away as it would be if the TextChanged event was used.
public class TextBoxImmediateUpdateBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
AssociatedObject.TextChanged += HandleAssociatedObjectTextChanged;
AssociatedObject.DataContextChanged += HandleAssociatedObjectDataContextChanged;
}
protected override void OnDetaching()
{
AssociatedObject.TextChanged -= HandleAssociatedObjectTextChanged;
AssociatedObject.DataContextChanged -= HandleAssociatedObjectDataContextChanged;
}
void HandleAssociatedObjectDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
hadNonemptyText = false;
}
void HandleAssociatedObjectTextChanged(object sender, TextChangedEventArgs e)
{
if (hadNonemptyText || AssociatedObject.Text != "")
{
var binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (binding != null) binding.UpdateSource();
hadNonemptyText = true;
}
}
Boolean hadNonemptyText = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment