简体   繁体   English

如何从ComboBox获取属性值?

[英]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. 因为下面的代码不起作用,因为我没有'Content'属性,所以我只有'name'属性。 Then how can I get value from name property? 那么如何从name属性中获取价值?

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. 它有效,谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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