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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With