【WPF】ComboBox:根据绑定选取、设置固定集合中的值
问题场景
我有一个对象,里面有一个属性叫Limit,int类型。虽然int可取的范围很大,我想要在用户界面上限制Limit可取的值,暂且限制为5、10、15、20。
所以ComboBox绑定不是绑定常见的ItemsSource(至少初看起来不是),而是Text、SelectedItem、SelectedValue或是什么东西,先卖个关子。
另外,Limit是表示时间的,单位秒。我要求ComboBox上能显示10秒、5秒,而不是光秃秃的10和5。
解决方案<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" Title="MainWindow" SizeToContent="WidthAndHeight"> <StackPanel Margin="10"> <StackPanel.Resources> <x:Array x:Key="candidateValues" Type="System:Int32"> <System:Int32>10</System:Int32> <System:Int32>15</System:Int32> <System:Int32>20</System:Int32> </x:Array> </StackPanel.Resources> <ComboBox Name="comboBox" ItemStringFormat="{}{0}秒" ItemsSource="{StaticResource candidateValues}" SelectedValue="{Binding Limit, RelativeSource={RelativeSource AncestorType=Window}}"> </ComboBox> <Button Content="读" Click="Button_Click" /> </StackPanel></Window>如上即可,记得删除MainWindow构造函数里给comboBox加元素的语句。
本文以知识共享-署名-相同方式共享方式发布
作者爱让一切都对了