Click here to Skip to main content
15,903,805 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to implement TextBox LostFocus event in my WPF window which should be fired in my ViewModel so that I can validate the value. Even parameter should be passed to the command. If we can use Attached Command Behavior, so anyone can please share an example.

Note: I am using MVVM pattern.

Regards,

Ramana
Posted
Updated 8-Dec-22 9:46am

Can be achieved by created Attached Behaviour.

C#
public class TextBoxBehavior
    {
        public static DependencyProperty OnLostFocusProperty = DependencyProperty.RegisterAttached(
            "OnLostFocus",
            typeof(ICommand),
            typeof(TextBoxBehavior),
            new UIPropertyMetadata(TextBoxBehavior.OnLostFocus));

        public static void SetOnLostFocus(DependencyObject target, ICommand value)
        {
            target.SetValue(TextBoxBehavior.OnLostFocusProperty, value);
        }

        /// <summary>
        /// PropertyChanged callback for OnDoubleClickProperty.  Hooks up an event handler with the 
        /// actual target.
        /// </summary>
        private static void OnLostFocus(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            var element = target as TextBox;
            if (element == null)
            {
                throw new InvalidOperationException("This behavior can be attached to a TextBox item only.");
            }

            if ((e.NewValue != null) && (e.OldValue == null))
            {
                element.LostFocus += OnPreviewLostFocus;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                element.LostFocus -= OnPreviewLostFocus;
            }
        }

        private static void OnPreviewLostFocus(object sender, RoutedEventArgs e)
        {
            UIElement element = (UIElement)sender;
            ICommand command = (ICommand)element.GetValue(TextBoxBehavior.OnLostFocusProperty);
            if (command != null)
            {
                command.Execute(e);
            }
        }
    }


XML
xmlns:ACB="clr-namespace:XML_Binding_Sample1.AttachedCommandBehaviour"

<textbox text="{Binding CustomerName}" acb:textboxbehavior.onlostfocus="{Binding  NameChangeCommand}" xmlns:acb="#unknown" />
 
Share this answer
 
Comments
Meer Deen 5-Sep-15 1:54am    
does't works for me
I was able to solve using interactivity behaviors.

XAML
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:vm="clr-namespace:myNameSpace.ViewModels"

<TextBox x:Name="myTextBox" Text="{Binding Source={StaticResource vm}, Path=myId}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="LostFocus">
            <i:InvokeCommandAction Command="{Binding Source={StaticResource vm}, Path=LostFocus}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>


VB.NET
Private _lostFocusCommand As ICommand
Private _myId as string

       Public Property MyId As String
           Get
               Return _myId
           End Get
           Set(value As String)
               _myId= value
               OnPropertyChanged("MyId")
           End Set
       End Property

       'DelegateCommand is a custom DelegateCommand class'

       Public ReadOnly Property LostFocus() As ICommand
           Get
               If _lostFocusCommand Is Nothing Then
                   _lostFocusCommand = New DelegateCommand(Function(c) OnLostFocus(), Nothing)
               End If
               Return _lostFocusCommand
           End Get

       End Property

       Private Function OnLostFocus()
           DoWork()
       End Function
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900