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(); };

            base.OnAttached();
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                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 =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                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
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 

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}" >
            <i:Interaction.Behaviors>
                <Local1:FocusBehavior HasInitialFocus="False" IsFocused="{Binding SaleOrderFocus, Mode=TwoWay}"/>
            </i:Interaction.Behaviors>


        </TextBox> 

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...

    ReplyDelete