简体   繁体   English

ComboBox.SelectedItem不是ComboBoxItem

[英]ComboBox.SelectedItem is not ComboBoxItem

I have ComboBox which I bind with list of some objects. 我有ComboBox,它与一些对象列表绑定在一起。 ComboBox.SelectedItem and ComboBox.SelectedValue return the same object instance but I was thinking SelectedItem should return ComboBoxItem . ComboBox.SelectedItemComboBox.SelectedValue返回相同的对象实例,但是我认为SelectedItem应该返回ComboBoxItem

The problem is that I want to get selected text but the object is not string so .ToString() will not work. 问题是我想获取选定的文本,但对象不是字符串,因此.ToString()将无法工作。

ComboBox.SelectedItem returns an instance of the type of objects in the list, so you'll have to cast it to the appropriate type and then select the display property of that instance. ComboBox.SelectedItem返回列表中对象类型的实例,因此您必须将其强制转换为适当的类型,然后选择该实例的display属性。

OR 要么

It should be sufficient just to call Combox.Text, but it requires that SelectedItem != null and a defined DisplayMemberPath on the ComboBox. 仅调用Combox.Text就足够了,但是它要求SelectedItem!= null和ComboBox上定义的DisplayMemberPath。

If you want the Selected text in the open TextBox you can use reflection: 如果要在打开的TextBox中选择文本,则可以使用反射:

  var propInfo = typeof(ComboBox).GetProperty("EditableTextBoxSite", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  var text = propInfo.GetValue(DataList) as TextBox;
  var selText = text.SelectedText;
  MessageBox.Show(selText);

You can bind SelectedItem to a property and set Selected value to that property when you make ComboBox SelectionChanged . 制作ComboBox SelectionChanged时,可以将SelectedItem绑定到属性,并将Selected值设置为该属性。

<ComboBox Name="cbxSalesPeriods"
                   Width="220" Height="30"
                   ItemsSource="{Binding SalesPeriods}"
                   SelectedItem="{Binding SelectedSalesPeriod}"
                   SelectionChanged="_ComboBoxCurrencyExchange_SelectionChanged">
        </ComboBox>

Here an ObservableCollection named SalesPeriods containing SalesPeriodV object is bound as an ItemsSource of that ComboBox . 在这里,包含SalesPeriodV对象的名为SalesPeriodsObservableCollection被绑定为该ComboBoxItemsSource

private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
    get { return salesPeriods; }
    set { salesPeriods = value; OnPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; OnPropertyChanged("SelectedItem"); }
}

private void _ComboBoxCurrencyExchange_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cb = (ComboBox)sender;
    SelectedItem = (SalesPeriodV)(cb.SelectedItem);
    string text = cb.SelectedValue.ToString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM