Edward Tanguay
Edward Tanguay

Reputation: 193452

How can I set the focus of a ListBox in XAML?

I have this ListBox:

<ListBox Name="lbColor">
    <ListBoxItem Content="Blue"/>
    <ListBoxItem Content="Red"/>
    <ListBoxItem Content="Orange"/>
</ListBox>

This code pre-selects the choice alright, but doesn't set the focus, how can I do that?

public Window1()
{
    InitializeComponent();

    lbColor.SelectedIndex = 1;
    lbColor.Focus = 1;
}

Upvotes: 0

Views: 869

Answers (2)

cordellcp3
cordellcp3

Reputation: 3623

I think, that you have to inherit from UIElement-Class and set true to UIElement.IsFocusable. Now you should be able to set the focus to the listbox with lblcolor.Focus()! I hope that this will help.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

You can use the Focus method:

public Window1()
{
    InitializeComponent();
    lbColor.SelectedIndex = 1;
    lbColor.Focus();
}

Upvotes: 3

Related Questions