古詩詞大全網 - 成語故事 - 如何讓下拉框ComboBox默認選中第壹項

如何讓下拉框ComboBox默認選中第壹項

但MVVM模式下,就不那麽方便了,需要綁定SelectedItem,例如:1:2:<ComboBoxItemsSource

={Binding Months}3:SelectedItem

={Binding Month, Mode=TwoWay}/  似乎可行,但如果是默認加載第壹項的話,這個SelectedItem就應該是綁定源更新以後的ItemSource.FirstOrDefault(),為何要雙向綁定呢?有壹點不太爽。有沒有其它辦法呢?很簡單,繼承ComboBox,寫壹個控件,讓它默認選中第壹項,就解決這個問題了,不用綁定SelectedItem。

<ComboBoxItemsSource

={Binding Months}/  自定義ComboBox控件代碼如下,也非常簡單,思路就是ItemSource更新以後就自動默認選中第壹行即可:1:publicclassCustomComboBox : ComboBox2:{3:/// <summary4:/// Initializes a new instance of the <see cref=CustomComboBox/ class.5:/// </summary6:publicCustomComboBox()7:{8:Loaded += ComboBoxLoaded;9:SelectionChanged += ComboBoxSelectionChanged;10:}11:12:voidComboBoxLoaded(objectsender, RoutedEventArgs e)13:{14:SetSelectedItem();15:}16:17:voidComboBoxSelectionChanged(objectsender, SelectionChangedEventArgs e)18:{19:SelectedItem = e.AddedItems.Count 0 ? e.AddedItems[0] :null;20:}21:22:publicnewobjectSelectedItem23:{24:get {return(object)GetValue(SelectedItemProperty); }25:set { SetValue(SelectedItemProperty,

value); }26:}27:28:publicnewstaticreadonlyDependencyProperty SelectedItemProperty =29:DependencyProperty.Register(

SelectedItem,

typeof(object),

typeof(CustomComboBox),

30:newPropertyMetadata((o, e) = ((CustomComboBox)o).SetSelectedItem()));31:32:privatevoidSetSelectedItem()33:{34:if(Items.Count 0)35:base

.SelectedIndex = 0;36:37://var value = SelectedItem;38://if (Items.Count 0 && value != null)39://{40:// base.SelectedIndex = Items.IndexOf(value);41://}42:}43:44:protectedoverridevoidOnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)45:{46:base

.OnItemsChanged(e);47:SetSelectedItem();48:}49:}  如果妳覺得代碼好用就拿過去,否則請分享更好的代碼。