我試圖獲取在其處理程序中的組合框中選定的值,以便我可以根據每次更改的值執行一些操作。但我無法將該值轉換爲整數。當我嘗試將其轉換爲字符串並將其打印在控制檯上時,如果選擇的值爲100000,則打印爲「System.Windows.Controls.ComboBoxItem:100000」。無法將組合框中的值轉換爲整數
請在下面找到XAML和處理程序代碼。
<ComboBox x:Name="Scale" HorizontalAlignment="Left" Margin="660,15,0,0" Grid.Row="1" VerticalAlignment="Top" Width="60" Height="26" SelectionChanged="Scale_SelectionChanged">
<ComboBoxItem Content="1" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="10" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="50" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="100" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="200" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="400" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="500" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="750" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="1000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="2000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="4000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="5000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="10000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="20000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="40000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="50000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="100000" HorizontalAlignment="Left" Width="60"/>
</ComboBox>
C#代碼
private void Scale_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Console.WriteLine(Scale.SelectedValue.ToString());
}
[組合框的獲取選擇的值]的可能的複製(http://stackoverflow.com/questions/6901070/getting-selected-value-of-a-combobox) –
另見[ http://stackoverflow.com/a/4902454](http://stackoverflow.com/a/4902454)的解釋。 –
WPF =綁定。不要像這樣創建'ComboBoxItem'。不要從View獲取值,而是直接從底層收集獲取值,那麼不需要任何投射。見例如[這個答案](http://stackoverflow.com/a/19632600/1997232),或[本教程](http://www.wpf-tutorial.com/list-controls/combobox-control/)。 – Sinatr