C# 将组合框中的值(从ObservableCollection填充)传递到另一个方法UWP

C# 将组合框中的值(从ObservableCollection填充)传递到另一个方法UWP,c#,combobox,uwp,observablecollection,C#,Combobox,Uwp,Observablecollection,我在main page.xmal中有一个组合框,它由一个ObservableCollection填充,并显示一个国家名称列表。我想做的是,当用户选择国家名称时,我想传递一个与每个国家关联的代码。名称和代码都存储在ObservableCollection中 我假设我可以在组合框中设置一个属性,该属性也允许我将所选项目设置为国家代码。任何帮助都会很好 <StackPanel Margin="10,100,0,0" Orientation="Vertical" >

我在main page.xmal中有一个组合框,它由一个ObservableCollection填充,并显示一个国家名称列表。我想做的是,当用户选择国家名称时,我想传递一个与每个国家关联的代码。名称和代码都存储在ObservableCollection中

我假设我可以在组合框中设置一个属性,该属性也允许我将所选项目设置为国家代码。任何帮助都会很好

     <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}"
            DisplayMemberPath="Name"
            SelectedValuePath="Code"
            MinWidth="250" Margin="5" Opacity="0.65">
        </ComboBox>
        <TextBox Name="CityTextBox" PlaceholderText="Enter City"/>
    </StackPanel>

 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.display_location.city + " _  " + myCityWeather.current_observation.temp_c.ToString() + "-" + myCityWeather.current_observation.wind_kph;

    }

私有异步void WeatherCityButton_Click(对象发送器,RoutedEventArgs e)
{
var city=CityTextBox.Text.ToString();
var country=countryCombo.SelectedValuePath.ToString();
RootObject myCityWeather=wait WeatherFacade.GetWeatherCity(国家、城市);
WeatherResultCityText.Text=myCityWeather.current\u observation.display\u location.city+“\u”+myCityWeather.current\u observation.temp\u c.ToString()+“-”+myCityWeather.current\u observation.wind\u kph;
}

您已经按照自己的意愿进行了设置-
SelectedValuePath
正是您所描述的。设置后,访问组合框的
SelectedValue
属性将提供所选项目的代码

您只需更改此行:

var country = countryCombo.SelectedValuePath.ToString();
致:


如果我没有弄错的话,您使用的方法将返回“Code”,因为您正在检索输入的相同值。

太好了,这非常有用。有时很难从树上看到木头。没问题——每个人都会时不时地遇到。请将其标记为答案,因为它对您有效3.
var country = countryCombo.SelectedValue.ToString();