-
最新的wpf的ComboBox设置默认值得方法是,给VM中的数据集合第一个元素插入一个提示项目,比如:请选择一项,然后通过数据绑定可以实现默认选中第一项,下面我就贴一下示例代码:xaml页面:
- <ComboBox Name="ResizeCanvas" SelectionChanged="ResizeCanvas_SelectionChanged" SelectedItem="{Binding Path=SelectedCanvasSize}" ItemsSource="{Binding Path=CnavasSizeList}" DisplayMemberPath="RatioText" SelectedValuePath="RatioValue"/>
相应的VM里面的数据源处理:这里页面不仅绑定了数据源,也绑定了ComboBox选中项,只要选中更改事件ResizeCanvas_SelectionChanged中去判断一下是不是为第一项就可以了,当选中第一项的时候不做处理 - public MainWindowViewModel()
- {
- CanvasSize canvasSize0 = new CanvasSize("请选中一项", 0.0);
- CanvasSize canvasSize1 = new CanvasSize("100%", 1.0);
- CanvasSize canvasSize2 = new CanvasSize("125%", 1.25);
- CanvasSize canvasSize3 = new CanvasSize("150%", 1.5);
- CnavasSizeList.Add(canvasSize1);
- CnavasSizeList.Add(canvasSize2);
- CnavasSizeList.Add(canvasSize3);
- selectedCanvasSize = canvasSize0;
- }
- private ObservableCollection<CanvasSize> canvasSizeList = new ObservableCollection<CanvasSize>();
- public ObservableCollection<CanvasSize> CnavasSizeList
- {
- get { return canvasSizeList; }
- set { canvasSizeList = value; OnPropertyChanged("CnavasSizeList"); }
- }
- private CanvasSize selectedCanvasSize;
- public CanvasSize SelectedCanvasSize
- {
- get { return selectedCanvasSize; }
- set { selectedCanvasSize = value; OnPropertyChanged("SelectedCanvasSize"); }
老方式,感觉不是很好用哈
在wpf里面简单的设置 ComboBox的text属性是不能设置它的默认选中的值的。在网上看到有人说可以设置默认选中项,设置它的selectedIndex="0".把第一项作为它的默认项。
在展开下拉框时,将第一项的visibility="collapsed"这样就行了。
<ComboBox Width="100" SelectedIndex="0">
<ComboBoxItem Content="Import" Visibility="Collapsed"></ComboBoxItem>
<ComboBoxItem Content="Import File" ></ComboBoxItem>
<ComboBoxItem Content="Import Folder"></ComboBoxItem>
</ComboBox>