2017-06-02 126 views
0

我认为ComboBox.SelectedItem.ToString()会工作,但它总是返回这个字符串:Windows.UI.Xaml.Controls.ComboBoxItem,而选定的项目的内容是不同的。如何获取ComboBox.SelectedItem的内容?

+1

您应该检查组合框的SelectedItem.Value或SelectedValue。 –

+2

对于ComboBox中的简单文本,使用'(comboBox.SelectedItem作为ComboBoxItem).Content.ToString()' – AVK

回答

0

这是一个简单的问题。 您要找的是ComboboxItem所选项目的dataContext。为了得到这个,

  1. 为Combobox创建一个SelectionChanged事件。
  2. 既然你有这个事件,它将提供两个方法参数(object senderEventArgs e)。
  3. sender投射到组合框(var container = sender as ComboBox)。
  4. 现在,拉出所选项目作为comboboxItemvar selected = container.SelectedItem as ComboBoxItem)。
  5. 现在从selectedItem中提取DataContext并将其转换为您提供的类型(一个字符串或您提供的某个类的类型)。

if (selected != null) 
{ 
    var dataYouNeed = selected.DataContext as TypeYouDefined; //(string or a class) 
    if (dataYouNeed != null) 
    { 
     //Do your stuff here 
    } 
} 

如果你有到ComboBox的直接访问,那么你并不需要的事件。 只需遵循以下代码。

var selected = MyComboBox.SelectedItem as ComboBoxItem; 
     if(selected!=null) 
     { 
      var dataYouNeed = selected.DataContext as TypeOfDataYouDifined; //string or some Class 
      if(dataYouNeed!=null) 
      { 
       //do your stuff here... 
      } 
     }