Ashot Khachatryan
Ashot Khachatryan

Reputation: 2366

ComboBox.SelectedItem is not ComboBoxItem

I have ComboBox which I bind with list of some objects. ComboBox.SelectedItem and ComboBox.SelectedValue return the same object instance but I was thinking SelectedItem should return ComboBoxItem.

The problem is that I want to get selected text but the object is not string so .ToString() will not work.

Upvotes: 1

Views: 587

Answers (2)

J. Hasan
J. Hasan

Reputation: 512

You can bind SelectedItem to a property and set Selected value to that property when you make ComboBox SelectionChanged.

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

Here an ObservableCollectionnamed SalesPeriods containing SalesPeriodV object is bound as an ItemsSource of that ComboBox.

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();
}

Upvotes: 1

user1562155
user1562155

Reputation:

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.

OR

It should be sufficient just to call Combox.Text, but it requires that SelectedItem != null and a defined DisplayMemberPath on the ComboBox.

If you want the Selected text in the open TextBox you can use reflection:

  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);

Upvotes: 1

Related Questions