2017-02-22 57 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