Sean McGrath Sean McGrath - 1 year ago 79
C# Question

Passing a value from a combobox, populated from an ObservableCollection into another method UWP

I have a combobox in my main page.xmal, it is populated from an ObservableCollection and displays a list of Country Names. What I want to happen is, When the user selects the name of the country, I want to pass a code which is assoicated with each country. The Name and the Code are both stored in the ObservableCollection.

I presume I can set a property in the combobox which allow me too, set the selected item equal to the country code. Any help would be great.

<StackPanel Margin="10,100,0,0" Orientation="Vertical" >
<ComboBox Name="countryCombo"
PlaceholderText="Select Country"
ItemsSource="{x:Bind ReadInFile.CountryCodes, Mode=OneWay}"
SelectedIndex="{x:Bind ReadInFile.SelectedIndex}"
MinWidth="250" Margin="5" Opacity="0.65">
<TextBox Name="CityTextBox" PlaceholderText="Enter City"/>

private async void WeatherCityButton_Click(object sender, RoutedEventArgs e)
var city = CityTextBox.Text.ToString();
var country = countryCombo.SelectedValuePath.ToString();

RootObject myCityWeather = await WeatherFacade.GetWeatherCity(country, city);

WeatherResultCityText.Text = + " _ " + myCityWeather.current_observation.temp_c.ToString() + "-" + myCityWeather.current_observation.wind_kph;


Answer Source

You've already got it set up how you want it - SelectedValuePath does precisely what you describe. Once that's set, accessing the ComboBox's SelectedValue property will provide the code for the selected item.

You need only to change this line:

var country = countryCombo.SelectedValuePath.ToString();


var country = countryCombo.SelectedValue.ToString();

The way you had it simply will return "Code", if I'm not mistaken, as you're retrieving the same value you put in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download