Set focus to UIElement (i.e. TextBox ) in XAML , using Silverlight 4?

4k views Asked by At

I have only seen code solutions to this problem. I am looking for a XAML based solution and I am quiet surprised you can't set focus on a UI element in XAML.

I found this old MSDN post: http://social.msdn.microsoft.com/Forums/en/wpf/thread/09dc837d-4485-4966-b45b-266727bbb90c

that had the solution I sought ( this is WPF only I guess )

<Grid FocusManager.FocusedElement="{Binding ElementName=listBox1}">

Is setting focus to a TextBox/ListBox in Silverlight 4 XAML not possible ?

2

There are 2 answers

1
Joe McBride On BEST ANSWER

As far as I know, no, there is not a way in XAML to set the focus of an element. You'll have to resort to something like you've referenced. I think an attached behavior (similar to the FocusManager) would be the best route.

0
Mike Post On

There is always a way in XAML, if you try hard enough. :) What you need is a Trigger, from the Blend SDK.

public class FocusTrigger : TargetedTriggerAction<Control>
{
   protected override void Invoke(object parameter)
   {
      if (Target == null)
         return;

      Target.Focus();
   }
}

Then to use it something like:

<Button Content="Move focus">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <local:FocusTrigger TargetName="TheTextBox"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>
<TextBox x:Name="TheTextBox"/>

If you want to get REALLY fancy, you can apply a condition to your trigger and do all sorts of crazy things in XAML. I will say I am surprised this sort of thing isn't built in though.