問題場景
我有一個對象,里面有一個屬性叫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" Title="MainWindow" SizeToContent="WidthAndHeight">
<StackPanel Margin="10">
<ComboBox Name="comboBox" ItemStringFormat="{}{0}秒" SelectedValue="{Binding Limit, RelativeSource={RelativeSource AncestorType=Window}}" />
<Button Content="讀" Click="Button_Click" />
</StackPanel>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
Limit = 10;
InitializeComponent();
comboBox.Items.Add(10);
comboBox.Items.Add(15);
comboBox.Items.Add(20);
comboBox.Items.Add(25);
}
public int Limit { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
//此處下斷點來看Limit到底變了沒有。
}
}
小結:使用ItemStringFormat來加上“秒”字,用SelectedValue選取值。
能不能用純XAML完成呢?
<ComboBox Name="comboBox" ItemStringFormat="{}{0}秒" SelectedValue="{Binding Limit, RelativeSource={RelativeSource AncestorType=Window}}">
<ComboBoxItem>
<System:Int32>10</System:Int32>
</ComboBoxItem>
<ComboBoxItem>
<System:Int32>15</System:Int32>
</ComboBoxItem>
<ComboBoxItem>
<System:Int32>20</System:Int32>
</ComboBoxItem>
<ComboBoxItem>
<System:Int32>25</System:Int32>
</ComboBoxItem>
</ComboBox>
以上方案是不行的!因為ComboBox的集合已經是ComboBoxItem,而不是int了。所以還得回歸ItemsSource。
<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加元素的語句。
本文以知識共享-署名-相同方式共享方式發布
作者愛讓一切都對了