views:

124

answers:

2

I have a listbox to which I have bound the data context to an object. This object has a number of properties some of which will have a particular attribute.

What I want to do from this is to have the items source set to the properties of the object but to only display those properties that have a particular attribute set.

Can anyone help with where I would start on this?

A: 

One way is to build your data context object dynamically and bind the Visibility properties to properties on this dynamically built object. You would then use it in the following way:

var provider = new MyDynamicProvider();
// Add the names of the properties with the particular attribute with 
// initial values (found using reflection elsewhere). 
provider.MyValues.Add("PropertyWithAttribute", "Test");
provider.MyValues.Add("PropertyWithAttributeVisibility", Visibility.Visible);
// Add properties that do not have the attribute
provider.MyValues.Add("PropertyWithoutAttributeVisibility", Visibility.Collapsed);
view.DataContext = provider.CreateDynamicWrapper();

In the view you can now do the following:

<TextBlock 
    Visibility="{Binding PropertyWithAttributeVisibility}" 
    Text="{Binding PropertyWithAttribute}" 
    />
Jakob Christensen
+2  A: 

You could use LINQ and reflection to get the values of the properties which have that attribute set:

Class1 class1 = new Class1 { Name = "Sam", DOB = DateTime.Now, SSN = "123" };

MyListBox.ItemsSource = from p in typeof(Class1).GetProperties()
                        where p.IsDefined(typeof(Att), false)
                        select p.GetValue(class1, null);

Name and DOB are marked as [Att] in my test, and their values are added to the ListBox. SSN is not.

Mike Pateras