[英]How to get selected text from WPF Combobox?
我正在嘗試從WPF ComboBox獲取文本,當它將選擇但無法獲取任何文本時。 以下是我嘗試過的代碼。 如果有人選擇我的內容,請幫助我從ComboBox獲取文本。 請注意,ComboBox將從正常運行的sql server加載數據!
我的XAML代碼是:
<ComboBox x:Name="comboID" TabIndex="27" SelectedValuePath="Content" SelectionChanged="comboID_SelectionChanged" HorizontalAlignment="Left" Margin="694,396,0,0" VerticalAlignment="Top" Width="165"/>
以下是我嘗試過的C#代碼示例:
string str1 = comboID.SelectedItem.ToString();
string str2 = comboID.SelectedValue.ToString();
string str3 = comboID.Text;
ComboBoxItem cmb = comboID.SelectedItem as ComboBoxItem;
var myVal = sender as ComboBox;
string value = comboID.SelectedItem as string;
使用此代碼而不是您的代碼在組合框中添加項目:
SqlConnection conn = new SqlConnection("your connection");
SqlCommand cmnd = new SqlCommand();
SqlDataReader sdr = null;
conn.Open();
cmnd.Connection = conn;
String query = "Select ID from Seller ORDER BY ID";
cmnd.CommandText = query;
sdr = cmnd.ExecuteReader();
while (sdr.Read())
{
comboID.Items.Add(sdr.GetString(0));
}
現在您可以使用:
string str = comboExporterID.SelectedItem.ToString();
我創建了一個簡單的代碼來給您一個大概的想法。
我的Xaml
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="350">
<StackPanel Orientation="Horizontal">
<Label Content="Select Item" x:Name="LblSelectNumber" MinWidth="50px" Margin="5"></Label>
<ComboBox x:Name="ComboId" DisplayMemberPath="Number"
SelectedValuePath="Content" SelectionChanged="ComboID_OnSelectionChanged" MinWidth="100"
HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" />
</StackPanel>
</Window>
我背后的代碼
public partial class MainWindow : Window
{
private readonly List<MyItem> _items;
public MainWindow()
{
InitializeComponent();
_items = new List<MyItem>
{
new MyItem{Content = "Test1",Number = "One"},
new MyItem{Content = "Test2",Number = "Two"},
new MyItem{Content = "Test3",Number = "Three"}
};
ComboId.ItemsSource = _items;
}
private void ComboID_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(ComboId.SelectedValue.ToString());
}
}
public class MyItem
{
public string Content { get; set; }
public string Number { get; set; }
}
請觀察ComboBox
中DisplayMemberPath
屬性的用法
一個簡單的建議。 創建應用程序時,請使用MVVM模式,因為它將長期幫助您維護解決方案。 使用MVVM模式,可以很容易地實現我上面所做的一切
簡單的代碼。 試試這個,應該可以
string s = comboID.text;
將Tag屬性添加到comboboxitems:
<Comboboxitem Tag="This Value"/>
然后
GetValue=ComboBoxName.SelectedItem.Tag.ToString()
GetValue將是“ This Value”,而不是System.windows.combobox等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.