Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on AND SELECT ALL of an initial text box (MVVM-Style)?

Tags:

focus

wpf

I have a simple WPF page with one text box field that my client wants highlighted when the page shows up. In code behind, it would be three lines, but I'm sogging through MVVM (which I'm starting to think is a little over-rated). I've tried so many different variants of behaviors and global events and FocusManager.FocusedElement, but nothing I do will do this.

Ultimately the most of the code I've been using calls these two lines:

Keyboard.Focus(textBox);
textBox.SelectAll();

But no matter where I put these lines the text box is only focused; no text is selected. I have never had this much trouble with something so simple. I've been hitting my head against the internets for two hours. Does anyone know how to do this?

Again, all I want to do is have the text box focus and it's text all selected when the page is navigated to. Please help!

like image 763
Jordan Avatar asked Oct 01 '22 22:10

Jordan


1 Answers

"Focus" and "Select All Text from a TextBox" is a View-specific concern.

Put that in code Behind. It does not break the MVVM separation at all.

public void WhateverControl_Loaded(stuff)
{
    Keyboard.Focus(textBox);
    textBox.SelectAll();
}

If you need to do it in response to a specific application/business logic. Create an Attached Property.

Or:

have your View resolve the ViewModel by:

this.DataContext as MyViewModel;

then create some event in the ViewModel to which you can hook:

public class MyViewModel
{
    public Action INeedToFocusStuff {get;set;}

    public void SomeLogic()
    {
        if (SomeCondition)
            INeedToFocusStuff();
    }
}

then hook it up in the View:

public void Window_Loaded(Or whatever)
{
    var vm = this.DataContext as MyViewModel;
    vm.INeedToFocusStuff += FocusMyStuff;
}

public void FocusMyStuff()
{
    WhateverTextBox.Focus();
}

See how this simple abstraction keeps View related stuff in the View and ViewModel related stuff in the ViewModel, while allowing them to interact. Keep it Simple. You don't need NASA's servers for a WPF app.


And no MVVM is not overrated, MVVM is extremely helpful and I would say even necessary. You'll quickly realize this as soon as you begin working with ItemsControls such as ListBoxes or DataGrids.

like image 159
Federico Berasategui Avatar answered Oct 05 '22 22:10

Federico Berasategui