WPF Combination with Bind to Int String

I want a Combobox with numbers 1-8 and bind the selected value to the "NumberOfZones" property of type int. By default, combobox returns a string value, so it cannot be stored in the int property. How do I enter text in an int.

How to set elements and make choices 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 the NumberOfZones property is the DataContext UserControl.

Thanks a lot.

+4
source share
3 answers

You are mistaken in returning a ComboBox . You are returning string values ​​due to what you have nested in it. If you instead create a property in which the NumberOfZones property was declared:

 public ObservableCollection<int> Numbers { get; set; } 

And then the data will contact 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 also be int .

+5
source

You can set the ItemsSource as an int array, then SelectedItem will be of type 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> 

for this you need to add the sys: namespace to your XAML:

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

I know that the question is about WPF, but just in case you are looking for an answer on 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> 

considering that

 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
+1
source

Source: https://habr.com/ru/post/1499596/


All Articles