永发信息网

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

答案:1  悬赏:20  手机版
解决时间 2021-01-24 16:09
  • 提问者网友:酱爆肉
  • 2021-01-24 00:52
[Siverlight入门系列]MVVM模式下如何让下拉框ComboBox默认选中第一项
最佳答案
  • 五星知识达人网友:你可爱的野爹
  • 2021-01-24 02:21
但MVVM模式下,就不那么方便了,需要绑定SelectedItem,例如:1:2:={Binding Months}3:SelectedItem
={Binding Month, Mode=TwoWay}/  似乎可行,但如果是默认加载第一项的话,这个SelectedItem就应该是绑定源更新以后的ItemSource.FirstOrDefault(),为何要双向绑定呢?有一点不太爽。有没有其它办法呢?很简单,继承ComboBox,写一个控件,让它默认选中第一项,就解决这个问题了,不用绑定SelectedItem。
  ={Binding Months}/  自定义ComboBox控件代码如下,也非常简单,思路就是ItemSource更新以后就自动默认选中第一行即可:1:publicclassCustomComboBox : ComboBox2:{3:/// 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:}  如果你觉得代码好用就拿过去,否则请分享更好的代码。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯