简体   繁体   中英

How to get property value from ComboBox?

How can I get property from this:

 <ComboBox x:Name="cmbCategory" Grid.Column="1" Grid.Row="5" HorizontalAlignment="Center" PlaceholderText="Categories">
     <ComboBox.ItemTemplate>
         <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <TextBlock TextWrapping="Wrap" Width="100%" Text="{Binding name}" />
             </StackPanel>
         </DataTemplate>
     </ComboBox.ItemTemplate>
 </ComboBox>

Because this code below doesn't work, because I don't have 'Content' property, I have only 'name' property. Then how can I get value from name property?

string categories= (cmbCategory.Items[cmbCategory.SelectedIndex] as ComboBoxItem).Content.ToString();

I figured it out.

I used this:

        public object GetPropertyValue(object car, string propertyName)
    {
        return car.GetType().GetProperties()
           .Single(pi => pi.Name == propertyName)
           .GetValue(car, null);
    }

Source: How to get a property value based on the name

Then I just use it like that:

string categories= GetPropertyValue(cmbCategory.Items[cmbCategory.SelectedIndex], "name").ToString();

It works, thanks everyone for help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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