简体   繁体   中英

c# WPF bind combobox to TPH in Entity Framework code first using LINQ

I'm building a WPF application using entity framework code first for the database. I need to bind my combobox to a TPH table that has a discriminator for two types of entity.

I've tried to query like this in XAML.CS :

 var pet = (from Pet in db.Pet.OfType<Dog>()
               select Pet).ToList();
 ComboBoxDog.ItemsSource = pet;

And my combobox in XAML

<ComboBox x:Name="ComboBoxDog" ItemsSource="{Binding Path = Name}" HorizontalAlignment="Left" Margin="203,81,0,0" VerticalAlignment="Top" Width="138" Height="28" SelectionChanged="cBoxServer_SelectionChanged"/>

If I remove Path=Name from combobox and .OfType<Server>() from my query it's showing values correctly, but without taking in considerations the discriminator. I would like to show only Name attribute.

You need to set the DisplayMemberPath ,DisplayMemberPath specifies the path to the display string property for each item. In your case

<ComboBox x:Name="cBoxServer" ItemsSource="{Binding}"  DisplayMemberPath="{Binding Name}" HorizontalAlignment="Left" Margin="203,81,0,0" VerticalAlignment="Top" Width="138" Height="28" SelectionChanged="cBoxServer_SelectionChanged"/>

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