带有字符串绑定到整型属性的WPF Combobox

10

我想要一个带有数字1-8的下拉列表,并将所选值绑定到类型为"NumberOfZones"的int属性。由于默认情况下,下拉列表返回字符串值,因此无法保存在int属性中。如何将其强制转换为int。

如何设置下拉列表项并进行整数选择。

   <ComboBox Background="#FFB7B39D" Height="23" Name="cboNumZones" Width="74" Margin="158,16,368,247" Grid.Row="2" SelectionChanged="cboNumZones_SelectionChanged" 
    SelectedValue="{Binding Path=NumberOfZones, Mode=TwoWay}">
   </ComboBox>
                <!--
                <ComboBoxItem >1</ComboBoxItem>
                    <ComboBoxItem >2</ComboBoxItem>
                    <ComboBoxItem >3</ComboBoxItem>
                    <ComboBoxItem >4</ComboBoxItem>
                    <ComboBoxItem >5</ComboBoxItem>
                    <ComboBoxItem >6</ComboBoxItem>
                    <ComboBoxItem >7</ComboBoxItem>
                    <ComboBoxItem >8</ComboBoxItem>
                -->

包含NumberOfZones属性的对象是UserControl的DataContext。

非常感谢。

3个回答

21

您可以将ItemsSource设置为整数数组,然后SelectedItem将为int32类型:

<ComboBox SelectedItem="{Binding Path=NumberOfZones, Mode=TwoWay}">             
   <ComboBox.ItemsSource>
      <x:Array Type="{x:Type sys:Int32}">
         <sys:Int32>1</sys:Int32>
         <sys:Int32>2</sys:Int32>
         <sys:Int32>3</sys:Int32>
         <sys:Int32>4</sys:Int32>
         <sys:Int32>5</sys:Int32>
         <sys:Int32>6</sys:Int32>
         <sys:Int32>7</sys:Int32>
         <sys:Int32>8</sys:Int32>
      </x:Array>
   </ComboBox.ItemsSource>
</ComboBox>

你需要在你的 XAML 中添加 sys: 命名空间:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

感谢您的回复。Sheridan的解决方案更适合我的应用程序。谢谢。 - Tvd
如果程序是64位构建的,这仍然有效吗? - Dave
@Dave 当然,这只是一个XAML语句。 - Adison

7
你对ComboBox返回值的理解是错误的。你所得到的是字符串类型,是因为你在其中输入的是字符串。如果你创建一个属性来代替NumberOfZones属性的话:
public ObservableCollection<int> Numbers { get; set; }

然后将数据绑定到您的 ComboBox

<ComboBox ItemSource="{Binding Numbers}" Background="#FFB7B39D" Height="23" 
    Name="cboNumZones" Width="74" Margin="158,16,368,247" Grid.Row="2" 
    SelectionChanged="cboNumZones_SelectionChanged" SelectedValue="{
    Binding Path=NumberOfZones, Mode=TwoWay}">

那么你选择的数字也将是一个int类型。


Sheridan,我错了。是的,你的代码像你说的那样工作,甚至双向绑定也成功了。这个解决方案解决了我的问题。我的另一个问题是 - 我想保持Numbers属性不变,因为它在应用程序的其他地方使用。我无法实现绑定。我在这里分享了它 - http://stackoverflow.com/questions/18493749/wpf-binding-combox-with-different-list-and-different-selectedvalue。如果您能提供类似的酷炫和最佳选项,请查看一下。 - Tvd

4

我知道这个问题是关于WPF的,但是以防你想在Windows 8.1 (WinRT, Universal Apps)上寻找答案,答案如下:

<ComboBox SelectedItem="{Binding NumberOfZones, Mode=TwoWay}">
    <x:Int32>1</x:Int32>
    <x:Int32>2</x:Int32>
    <x:Int32>3</x:Int32>
    <x:Int32>4</x:Int32>
    <x:Int32>5</x:Int32>
</ComboBox>

鉴于这一点,
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接