具有字符串“绑定到Int”属性的WPF组合框

本文关键字:属性 WPF 组合 Int 绑定到 字符串 绑定 | 更新日期: 2023-09-27 18:29:40

我想要一个数字为1-8的组合框,并将所选值绑定到int类型的属性"NumberOfZones"。默认情况下,combobox返回字符串值,因此无法将其保存在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。

非常感谢。

具有字符串“绑定到Int”属性的WPF组合框

您可以将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>

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

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

您对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

我知道这个问题是针对WPF的,但如果你在Windows 8.1(WinRT,通用应用程序)上寻找答案,那就是:

<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"