I want a Combobox with numbers 1-8 and bind the selected value to a property "NumberOfZones" of int type. By default, combobox returns string value so this can't be saved in int property. How do I type cast it to int.
How do I set items and make selection in 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>
-->
The object that contains NumberOfZones property is the DataContext of the UserControl.
Many Many Thanks.
You can set ItemsSource
as array of int, then SelectedItem
will be of int32
type:
<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>
for this you'll need to add sys:
namespace to your XAML:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
You are mistaken about what a ComboBox
returns. Yours returns string values because that's what you put into it. If instead you create a property where your NumberOfZones
property was declared:
public ObservableCollection<int> Numbers { get; set; }
And then data bind that to your 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}">
Then your selected number will be an int
too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With