1

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.

enter image description here

But I need the result should be like below image

enter image description here

What have I missed in the this list box code?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Shri
  • 63
  • 3
  • 9
  • 2
    Are you sure the difference between the two images is not because one of them has focus and the other one does not? In this case use the solution presented [here](http://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model-c) – rmojab63 Feb 22 '17 at 06:31
  • Listbox selectedIndex="0" it set first item selected . I think you need to set focus for the selected item . – Ragavan Feb 22 '17 at 06:35

2 Answers2

1

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.

snys98
  • 96
  • 4
-1

it seems ListboxItem not focused . Please Set ListBox to focus and item to focus

listBox.Focus();
var listBoxItem = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem);
listBoxItem.Focus();
Ragavan
  • 2,984
  • 5
  • 22
  • 24