Created
January 11, 2014 23:39
-
-
Save jtheisen/8378460 to your computer and use it in GitHub Desktop.
A behavior making a TextBox update the source on every key press.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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