0
votes

I have a WPF with the following listbox item definition:

<ListBoxItem Margin="5,2,5,2" Selector.IsSelected="True">
   <Button BorderThickness="0" 
      HorizontalAlignment="Stretch"
      HorizontalContentAlignment="Left"
      Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
      Command="{Binding ShowUsersCommand}">
        <TextBlock HorizontalAlignment="Left">USERS</TextBlock>
    </Button>
</ListBoxItem>

By default, the first item is selected when WPF window loads/appears. I can't seem to figure out how to make sure that first item is correctly highlighted. If I click listbox items, they display correctly as highlighted.

How do I at load time, select the first item in my listbox and display it as highlighted?

Thanks

2

2 Answers

1
votes
<ListBox SelectedIndex="0" />

In code behind you can add

 if (this.lst.Items.Count > 0)
        this.lst.SelectedIndex = 0;
0
votes

I assume you mean you want the program to focus on the item as well as selecting it, check this code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        listBox1.SelectedIndex = 0;
        ListBoxItem TestItem = new ListBoxItem();
        TestItem = (ListBoxItem)listBox1.SelectedItem;
        TestItem.Focus();
    }
}