[英]how to get value from dynamically added combobox in wpf c#?
I want get the data from combobox in WPF.我想从 WPF 中的组合框获取数据。
below is mu sample code.下面是 mu 示例代码。
<ComboBox Name="cmbCompanies" Height="110" Width="560" HorizontalAlignment="Right" SelectionChanged="cmbCompanies_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
my code-behind is:我的代码隐藏是:
to bind the data to combobox:将数据绑定到组合框:
JArray companies = (JArray)response["data"];
System.Diagnostics.Debug.WriteLine(companies.Count);
if (companies.Count == 0)
{
// alert no compaies associated with this account.
}
else
{
System.Diagnostics.Debug.WriteLine(companies);
for (int i = 0; i < companies.Count; i++)
{
Companies com = new Companies();
com.Id = (string)companies[i]["id"];
com.Name = (string)companies[i]["name"];
cmbCompanies.Items.Add(com);
}
to get the data:获取数据:
private void cmbCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
string item = (sender as ComboBox).SelectedItem.ToString();
string tmp = (cmbCompanies.SelectedValue as ComboBoxItem).Content.ToString();
}
I am trying the above code but i am getting the any values, please help on this.我正在尝试上面的代码,但我得到了任何值,请对此提供帮助。
Do some reading about Data Binding in WPF.阅读有关 WPF 中数据绑定的一些内容。 Create an object to be used as a ViewModel.
创建一个对象以用作 ViewModel。 Inside of the ViewModel add a property of a collection type (Observablecollection works).
在 ViewModel 内部添加一个集合类型的属性(Observablecollection 有效)。 Bind the ItemsSource property of the ComboBox to your collection.
将 ComboBox 的 ItemsSource 属性绑定到您的集合。 Anything you add to your collection from now on will appear in your ComboBox
从现在开始,您添加到收藏中的任何内容都将出现在您的 ComboBox 中
Cast the SelectedItem
property to a Companies
object:将
SelectedItem
属性转换为Companies
对象:
private void cmbCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Companies selectedCompany = (sender as ComboBox).SelectedItem as Companies;
if (selectedCompany != null)
{
string id = selectedCompany.Id;
string name = selectedCompany.Name;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.