[英]How to get text from Combo box c# Wpf?
每当我尝试从组合框中获取文本时,它都会提取System.Windows.Controls.ComboBoxItem: Abc
数据System.Windows.Controls.ComboBoxItem: Abc
我怎样才能只获得“ Abc”? 我的意思是说只值而不是整个堆栈跟踪。 我的代码似乎是:-
XAML:
<StackPanel Orientation="Horizontal" Width="auto" HorizontalAlignment="Center" Margin="0,10,0,0">
<TextBlock HorizontalAlignment="Left" FontFamily="/Vegomart;component/Images/#My type of font" Text="User Type:- " FontSize="18" Foreground="Black"/>
<ComboBox x:Name="userType" HorizontalAlignment="Right" FontFamily="/Vegomart;component/Images/#My type of font" Width="170" FontSize="18" Foreground="Black" Margin="40,0,0,0" >
<ComboBoxItem> Abc</ComboBoxItem>
</ComboBox>
</StackPanel>
C#:-
string value = userType.SelectedItem.ToString();
System.Diagnostics.Debug.WriteLine(value);
您的努力将不胜感激:)。
谢谢,
<ComboBox x:Name="userType" SelectionChanged="userType_SelectionChanged">
<ComboBoxItem Content="Abc"/>
<ComboBoxItem>Bcd</ComboBoxItem>
</ComboBox>
然后在后面的代码中:
private void userType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var comboBoxItem = comboBox.SelectedItem as ComboBoxItem;
if (comboBoxItem != null)
{
var content = comboBoxItem.Content;
System.Diagnostics.Debug.WriteLine(content);
}
}
}
<ComboBoxItem> Abc</ComboBoxItem>
将Content
设置为Abc
,因此您需要将SelectedItem
为ComboBoxItem
并获取该属性。
(XAML设置内容可以在基类ContentControl
看到,该基类具有一个ContentPropertyAttribute
,用于定义要设置的属性。)
您可以获得项目的内容:
ComboBoxItem item = (ComboBoxItem)userType.SelectedItem;
string value = (string)item.Content;
System.Diagnostics.Debug.WriteLine(value);
这将返回ComboBox中所选项目的文本。
string value = userType.Text.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.