2017-02-22 154 views
1

在我的解决方案,我已经为列表中的默认值,如下面的代码设置默认值列表框

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

建立在我看来模型SelectedDeviceItem财产。

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

,并传入构造SelectedDeviceItem = StatusList[0]; 。 但我的列表框仍然会显示如下。

enter image description here

但我需要的结果应该是像下面的图片

enter image description here

我有什么在这个列表框代码错过了什么?

+2

你确定两幅图像之间的差异不是因为其中一幅具有焦点而另一幅没有?在这种情况下,请使用[在此提供的解决方案](http://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model-c) – Ron

+0

Listbox selectedIndex =“0”它设置了第一个项目。我认为你需要为选定的项目设置焦点。 – Ragavan

回答

1

我认为这可能实现它:

  1. 设置所选ListBoxItem被聚焦。

    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. 加载ListBox时设置焦点。这是因为ListBoxItems可能在生成之前被选中。

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

注意,被选做项目的逻辑不应在视图模型来实现,它只是类型的UI逻辑。

-1

似乎ListboxItem没有集中。请设置列表框聚焦和项目集中

listBox.Focus(); 
var listBoxItem = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem); 
listBoxItem.Focus(); 
+0

在MVVM中设置焦点比较困难。 – Ron

+0

本身不是MVVM,但是应该在何处放置这些代码以实现预期的结果?它没有给出答案。 – OmegaMan