SideSky
SideSky

Reputation: 343

WPF get selected Combobox value which is bound to observablecollection

I have a ComboBox (CBaddress) which is bound to an ObservableCollection.

XAML

<ComboBox
   x:Name="CBaddress"
   Height="23"
   Margin="80,75,423,0"
   VerticalAlignment="Top" 
   ItemTemplate="{StaticResource AddressTemplate}"
   ItemsSource="{Binding}"
/>

<DataTemplate x:Key="AddressTemplate">
   <StackPanel Orientation="Horizontal">
      <TextBlock Width="50" Text="{Binding Path=ID_}" />
      <TextBlock Width="100" Text="{Binding Path=Address_}" />
      <TextBlock Width="30" Text="{Binding Path=HouseNumber_}" />
      <TextBlock Width="40" Text="{Binding Path=PostalCode_}" />
      <TextBlock Width="150" Text="{Binding Path=State_}" />
   </StackPanel>
</DataTemplate>

The ObservableCollection consists of a class (Address).

class Address
{
   public int ID_ { get; set; }
   public string Country_ { get; set; }
   public string State_ { get; set; }
   public int PostalCode_ { get; set; }
   public string Address_ { get; set; }
   public int HouseNumber_ { get; set; }
}

When my program starts it loads all values from a database and can display all values perfectly in the ComboBox:

CBaddress.DataContext = database.SelectAllAddresses();

But how do I get the values? With CBaddress.Text I get only this output :

MySQL_WPF.classes.Address

Is it possible to get the plain text, which is also displayed in the ComboBox?

It would be best if I could get a certain value from the selected value, like the ID_.

Upvotes: 0

Views: 758

Answers (1)

thatguy
thatguy

Reputation: 22119

If you want to get the selected item, access it with the SelectedItem property on ComboBox.

var selectedID = ((Address)CBaddress.SelectedItem).ID_ ;

The SelectedItem property is of type object, so you need to cast it to your data type Address. Then you can access any of its properties as usual.

If you are working in an MVVM scenario, you would bind the SelectedItem to a property on your view model, e.g. SelectedAddress.

<ComboBox ...
          ItemsSource="{Binding}"
          SelectedItem={Binding SelectedAddress}"/>
private Address _selectedAddress;
public Address SelectedAddress
{
   get => _selectedAddress;
   set
   {
      if (_selectedAddress == value)
         return;

      _selectedAddress = value;
      OnPropertyChanged();
   }
}

Then you could access any property the same way, e.g.:

var selectedID = SelectedAddress.ID_;

Upvotes: 1

Related Questions