Ich möchte meine ComboBox
in XAML an meine List
Sammlung von benutzerdefinierten Objekten im Code hinter zu binden.WPF: ComboBox zeigt "(Namespace). (Klassenname)" anstelle von Daten
Derzeit die ComboBox
Listen für jeden Eintrag dpwpf.Contact
, die meine {namespace}.{classname}
ist.
Was muss ich in den XAML eingeben, um es aufzulisten, z. Nachname + Vorname?
Ich weiß, es ist so etwas wie {Binding Path=... Value=...}
, aber ich kann es nicht bekommen.
XAML:
<Window x:Class="dpwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<StackPanel>
<TextBlock Text="Select the contact:"/>
<ComboBox Name="theContactList"/>
</StackPanel>
</StackPanel>
</Window>
-Code Behind:
namespace dpwpf
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
StoreDB db = new StoreDB();
List<Contact> contacts = db.GetContacts()
theContactList.ItemsSource = contacts.ToList();
}
}
}
Antwort:
<Window x:Class="dpwpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:dpwpf">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Contact}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding FirstName}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<StackPanel Margin="10">
<TextBlock Text="Contact Name:" Foreground="#555"/>
<TextBox Name="theName"/>
</StackPanel>
<StackPanel>
<TextBlock Text="Select the contact:"/>
<ComboBox Name="theContactList"/>
</StackPanel>
</StackPanel>
</Window>
Mögliche Duplikat [WPF IsEditable = true ComboBox gefüllt mit Objekten zeigt die ToString() als das ausgewählte Element] (https://stackoverflow.com/questions/1844156/wpf- iseditable-true-combobox-filled-with-objects-zeigt-the-tostring-as-the) –