WPF Combobox,字符串Bind为Int属性

Tvd*_*Tvd 5 c# string wpf int combobox

我想要一个数字为1-8的Combobox,并将所选值绑定到int类型的属性"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>
                -->
Run Code Online (Sandbox Code Playgroud)

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

非常感谢.

dko*_*ozl 13

您可以设置ItemsSource为int数组,然后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>
Run Code Online (Sandbox Code Playgroud)

为此,您需要将sys:命名空间添加到XAML:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
Run Code Online (Sandbox Code Playgroud)


She*_*dan 5

你错了什么ComboBox回报.你的返回字符串值,因为这是你放入它的内容.相反,如果您创建了NumberOfZones声明属性的属性:

public ObservableCollection<int> Numbers { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后数据绑定到您的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}">
Run Code Online (Sandbox Code Playgroud)

那么你选择的号码int也是.