Skip to main content
Home Forums Silverlight Programming Programming with .NET - General Is this a ValueConverter scenario?
4 replies. Latest Post by IanBlackburn on October 22, 2008.
(0)
R3al1ty
Member
185 points
72 Posts
10-16-2008 10:45 PM |
I have a Person class as below. The person's CountryID is bound to a ComboBox. The data is stored internally as IDs that need to be looked up in the Codes class to show the human readable text in the ComboBox (France, Japan etc rather than 1,2). Is this a good scenario to use a ValueConvertor and any pointers on how to structure it as there will be multiple entities to lookup in different scenarios (Country,Occupation etc)? public class Person{public int CountryID { get; set; }public int OccupationID { get; set; }}
public
public class Codes{public int Code { get; set; }public string Decode { get; set; }}
new Code( 1, "France" )new Code( 2, "Japan" )
IanBlack...
Contributor
2333 points
371 Posts
10-18-2008 1:07 PM |
Possible, though I think I would prefer to provide the correct data in the first place. You could use linq to build a new object with the data you need in it. For example:
List<Person> people = new List<Person>(); List<Codes> codes = new List<Codes>(); //TODO: populate people and codes with data...
var results = from p in people join c in codes on p.CountryID equals c.Code select new { p.CountryID, c.Code }; ListBox1.ItemsSource = results;
manish.d...
99 points
21 Posts
10-19-2008 7:24 PM |
You need to add one more property to Person class and expose Code as value of that property. Once that is done, you can databind SelectedItem property of ComboBox to the newly added property and DisplayMemberPath to the Description of Code. You can find details in my blog post on the same topic
http://feeds.feedburner.com/~r/ManishDalal/~3/417137421/combobox-in-datagrid.aspx
10-19-2008 8:55 PM |
Thanks Manish, excellent series of articles. I went down the route of adding SelectedValue to my controls rather than modify my data access classes. For lists, I use SelectedValue and for single item binding like textboxes, I use a custom ValueConverter.
Ian, when used across the whole app, I think it might clutter up the code a bit with custom joins for each binding. I'm also not sure how the CLR does mem management for strings; if I have one string object (e.g. 'France') in 100 objects, are there 100 instances in memory of the string?
10-22-2008 2:53 AM |
Using the linq expression to create the datasource would indeed require more memory, but the binding would be quicker than using the ValueConvertor because the computation is done in advance. So I guess it depends on where you need to optimise, and what you feel is more maintainable.