Social Icons

Thursday, January 19, 2012

How to set textbox focus in silverlight using MVVM

The question has been asked a couple of times, unfortunately the answers only apply to WPF. Anyone know how to accomplish this in silverlight? Basically I need to focus on a certain textbox from code.

Following class is required in view model

public class FocusBehavior : Behavior

        protected override void OnAttached()
            AssociatedObject.GotFocus += (sender, args) => IsFocused = true;
            AssociatedObject.LostFocus += (sender, a) => IsFocused = false;
            AssociatedObject.Loaded += (o, a) => { if (HasInitialFocus || IsFocused) AssociatedObject.Focus(); };


        public static readonly DependencyProperty IsFocusedProperty =
                new PropertyMetadata(false, (d, e) => { if ((bool)e.NewValue) ((FocusBehavior)d).AssociatedObject.Focus(); }));

        public bool IsFocused
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }

        public static readonly DependencyProperty HasInitialFocusProperty =
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }

Add name space reference in Xaml file like as

and give initial value and binding value like as below
 <TextBlock Height="20" HorizontalAlignment="Left" Margin="10,16,0,0" Text="Sales Order No" TextWrapping="Wrap" VerticalAlignment="Top" Width="91" />
        <TextBox Height="22"  HorizontalAlignment="Left" Margin="115,13,0,0" MaxLength="20" Name="txtSalesOrderNo" TabIndex="0"  TextWrapping="Wrap" VerticalAlignment="Top" Width="165" Text="{Binding Path=SaleOrderNo, Mode=TwoWay}" >
                <Local1:FocusBehavior HasInitialFocus="False" IsFocused="{Binding SaleOrderFocus, Mode=TwoWay}"/>


1 comment:

  1. "Local1:FocusBehavior" is blue lined Error : the type "Local1:FocusBehavior" was not found. Veryfy that u r not missing an asembly referenece...



Sample text

Sample Text