2011-09-29 91 views
10

我正在尋找在數據可用時選擇第一個項目的方法。但如果源中沒有數據,則不要選擇。怎麼做 ?我對WPF很陌生。當數據可用時,Comboxbox自動選擇第一個項目

<ComboBox Grid.Row="5" Grid.Column="1" 
      IsEditable="False" 
      ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}" 
      ToolTip="Resolutions"> 
    <ComboBox.Resources> 
     <l:ResolutionConverter x:Key="resolutionConverter"/> 
    </ComboBox.Resources> 
    <ComboBox.Text> 
     <MultiBinding Converter="{StaticResource resolutionConverter}"> 
      <Binding Path="GameWidth" Mode="OneWayToSource"/> 
      <Binding Path="GameHeight" Mode="OneWayToSource"/> 
     </MultiBinding> 
    </ComboBox.Text> 
</ComboBox> 
+0

是否有任何種類的Itemssource(Resolutions)可用的更改通知? – RQDQ

+0

該商品來源僅限於列表。不知道它是否有更改通知。如何添加更改通知? –

回答

22

最簡單的方法是使用SelectedIndex。請檢查下面的代碼。

<ComboBox Grid.Row="5" Grid.Column="1" 
      IsEditable="False" 
      ItemsSource="{Binding Source={x:Static l:DirectXResolution.Resolutions}}" 
      ToolTip="Resolutions" 
      SelectedIndex="0"> 
.... 
+8

不完全正確..如果要重新填充項目列表,則需要IsSynchronizedWithCurrentItem =「true」,否則將不會自動選擇第一個索引。 – user384080

1

DirectXResolution.Resolutions必須ObservableCollection<T>否則你當數據變爲可用ComboBox將不會被更新。您可以使用CollectionChanged事件ObservableCollection<T>選擇第一個項目。

如果DirectXResolution.ResolutionsObservableCollection,創建這個集合的包裝和繼承INotifyCollectionChanged

0

這裏是如何做到這一點的代碼:

Items.CollectionChanged += (sender, e) => 
{ 
    if (!Items.Contains(Selected)) 
    { 
     Selected = Items.FirstOrDefault(); 
    } 
}; 

ItemsObservableCollection可以更新。 Selected是所選項目的雙向屬性。這段代碼應該放在視圖模型的構造函數中。

相關問題