ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

SetInitialFocus

Set the initial focus for a Silverlight ChildWindow.

Source

/// <summary>
/// Set the initial focus on the given control
/// </summary>
/// <param name="window">Childwindow for which te focus must be set</param>
/// <param name="focus">Control to set the focus on</param>
public static void SetInitialFocus(this ChildWindow window, Control focus) {
    RoutedEventHandler fp = null; // set to null to prevent unassigned compiler error
    fp = delegate {
        focus.Focus();
        var tb = focus as TextBox;
        if (tb != null) {
            tb.SelectAll();
        }
        // unsubscribe after first execute
        window.GotFocus -= fp;
    };

    window.GotFocus += fp;
}

Example

public partial class DemoWindow : ChildWindow {

public DemoWindow() {
    InitializeComponent();

    this.SetInitialFocus(this.TextBoxFirstname);
}

...

Author: Fons Sonnemans

Submitted on: 24 feb. 2010

Language: C#

Type: System.Windows.Controls.ChildWindow

Views: 5078