Click here to Skip to main content
16,017,650 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am doing something wrong .. you know how it is.

I have simplified the problem as I am having difficulty in general with databinding generics.

I have created a simple Generic List of Person and want to bind it to a combo. (also want to try use a ListView too).

I either get a list of blanks or a list of 'xxxx.Person' where xxxx = namespace

<Window x:Class="BindingGenerics.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Grid>

<ComboBox Name="ComboBox1"
ItemsSource="{Binding}"
Height="50"
DisplayMemberPath="Name"
SelectedValuePath="ID"
FontSize="14"
VerticalAlignment="Top">
</ComboBox>

</Grid>
</Window>

using System.Windows;
using System.ComponentModel;
namespace BindingGenerics
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person p = new Person();
// I have tried List and BindingList
//List<Person> list = new List<Person>();
BindingList<Person> list = new BindingList<Person>();
p.Name = "aaaa";
p.ID = "1111";
list.Add(p);
p = new Person();
p.Name = "bbbb";
p.ID = "2222";
list.Add(p);
p = new Person();
p.Name = "cccc";
p.ID = "3333";
list.Add(p);
p = new Person();
p.Name = "dddd";
p.ID = "4444";
list.Add(p);
ComboBox1.DataContext = list;
}
}
public struct Person
{
public string Name;
public string ID;
}
Posted
Updated 15-Feb-10 18:07pm
v6

You need to create a template for your listbox, so that it knows how to display a person object. If you don't tell it, it calls ToString() and gets back the class name. Some controls have a DisplayMember property which you set to the property you want to show, but I don't think that happens in WPF.
 
Share this answer
 
Post your code for your Person class/struct. If it is a class, it looks like you are adding the same person to the list repeatedly (rather than creating a new instance each time).
 
Share this answer
 
There was an error in the example .. I was actually newing each Person .. just an error in writing eample here.. thanks


SOLVED SOLVED SLOVED

the generics list was a list of structs

if you use a class instead of a struct it works fine

i.e.

public class Person
{
public string Name { get; set;}
public string ID { get; set;}
}
instead of

public struct Person
{
public string Name;
public string ID;
}
 
Share this answer
 
v2
The reason it doesn't work is likely that you are using variables rather than properties on your struct.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900