[Siverlight入门系列]MVVM模式下如何让下拉框ComboBox默认选中第一项

 我来答
百度网友0eca1c692ae
2013-11-08 · 超过62用户采纳过TA的回答
知道答主
回答量:124
采纳率:0%
帮助的人:154万
展开全部
但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:}  如果你觉得代码好用就拿过去,否则请分享更好的代码。
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式