Set the default value for ListBox

advertisements

In my solution I have set the default value for list like below code

<ListBox x:Name="SelectorList"
         ItemsSource="{Binding ViewStatusList}"
         SelectedItem="{Binding SelectedDeviceItem,Mode=TwoWay}"
         IsSynchronizedWithCurrentItem="True">

create the property for SelectedDeviceItem in my view model.

private Device _selecteddeviceitem;
public Device SelectedDeviceItem
{
    get
    {
        return _selecteddeviceitem;
    }
    set
    {
        _selecteddeviceitem = value;
        OnPropertyChanged("SelectedDeviceItem");
    }
}

and passed SelectedDeviceItem = StatusList[0]; in the constructor. But still my listbox will be shown like below.

But I need the result should be like below image

What have I missed in the this list box code?


I think this could achieve it:

  1. Set the selected ListBoxItem to be focused.

    private void ListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    
        var listbox = sender as ListBox;
        var listboxItem =
            listbox?.ItemContainerGenerator.ContainerFromItem(listbox.SelectedItem) as ListBoxItem;
        listboxItem?.Focus();
    }
    
    
  2. Set focus when the ListBox loaded. This is because that the ListBoxItems may be selected before they are generated.

    private void ListBox_Loaded(object sender, RoutedEventArgs e)
    {
        var listbox = sender as ListBox;
        var listboxItem =
            listbox?.ItemContainerGenerator.ContainerFromItem(listbox.SelectedItem) as ListBoxItem;
        listboxItem?.Focus();
    }
    
    

Note that the logic of making item being selected should not be achieved in the view model, it's just kind of a UI logic.