files

Code Snippets

The requested snippet is shown below

Title: Update textbox binding from IsDefault button press
Description: This attached behaviour triggers the update of the binding source when the user trggers an IsDefault button press without losing focus.
Category: WPF

Get link for this code snippet
Collapse code snippet
Expand code snippet
using System.Windows.Interactivity;
    using System.Windows.Controls;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Data;
    /// <summary>
    /// Associate this behaviour with the button that you mark as IsDefault
    /// to trigger the ViewModel update when the user clicks enter in a textbox
    /// and the property doesn't update because the update source is set to
    /// lost focus.
    /// </summary>
    public class DefaultButtonUpdateTextBoxBindingBehavior : Behavior<Button>
    {
        /// <summary>
        /// Hook into the button click event.
        /// </summary>
        protected override void OnAttached()
        {
            AssociatedObject.Click += AssociatedObject_Click;
            base.OnAttached();
        }

        /// <summary>
        /// Unhook the button click event.
        /// </summary>
        protected override void OnDetaching()
        {
            AssociatedObject.Click -= AssociatedObject_Click;
        }

        /// <summary>
        /// The click event handler.
        /// </summary>
        void AssociatedObject_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // Get the element with the keyboard focus
            FrameworkElement el = Keyboard.FocusedElement as FrameworkElement;
            if (el != null && el is TextBox)
            {
                // Get the binding expression associated with the text property
                // for this element.
                BindingExpression expression = el.GetBindingExpression(TextBox.TextProperty);
                if (expression != null)
                {
                    // Now, trigger the update.
                    expression.UpdateSource();
                }
            }
        }
    }