1

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();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
ktos1234
  • 197
  • 1
  • 6
  • 22
  • 1
    To get a `TextBlock` inside a `ComboBox.ItemTemplate` and change it's properties in code you should use `FrameworkTemplate.FindName` Method. The answer of this question is here: http://stackoverflow.com/questions/34117944/listbox-items-return-string-when-datatemplate-is-button – Salah Akbari May 10 '16 at 20:24

1 Answers1

0

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.

Community
  • 1
  • 1
ktos1234
  • 197
  • 1
  • 6
  • 22