This is a mirror of official site: http://jasper-net.blogspot.com/

Setting focus on a control in Silverlight using XAML

| Sunday, July 10, 2011
Introduction

When I first started using Silverlight, I was amazed that there wasn't an easy way to set the focus of the cursor to a text box. I had just built a login page and wanted the cursor to default to the user name text box. After searching blogs and forums, I've finally come up with a solution that satisfies me. I hope this article helps you avoid the frustrations of some of the one-line responses you will see in some of the forum responses.
Background

The basis on my solution is to leverage a trigger action to invoke the Focus() method on a control and then use event triggers to execute that trigger action. The attached example includes the SetFocusTrigger and examples of using it via the Loaded event, Click event, and the (potentially contentious) DataTrigger. I'll talk about the DataTrigger a bit more at the end of the article, particularly to appease the MVVMers out there that are screaming "the view model shouldn't tell the view which control should have focus".

Since we're talking MVVM, of which I'm a huge fan, I'll just raise that I didn't make the attached source code example a MVVM application, to keep it simple. I would strongly recommend that you don't set a DataContext the way I have in the example. There are plenty of good articles to show you the right way.
Using the code

The first issue we should resolve before we get into the trigger and XAML, is to set the focus on the Silverlight plug-in. If we don't do that at the very start of the application loading then you can set the focus on a control as many times as you like, but you won't see the cursor until you click on the Silverlight application (effectively manually setting the focus on the Silverlight plug-in). The common way to do this is to use the HtmlPage static class to set the plug-in focus, in the starting page (for example, the MainPage.xaml).

public MainPage()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(OnLoaded);
}

void OnLoaded(object sender, RoutedEventArgs e)
{
    HtmlPage.Plugin.Focus();
}

Of couse, if you're running your application out-of-browser, you don't need the code above (in fact, it will throw an exception).

Read more: Codeproject
QR: SilverlightSetFocusInXaml.aspx

Posted via email from Jasper-net

0 comments: