开发者

WPF Binding to properties of an object with specific attributes

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 hel开发者_开发问答p with where I would start on this?


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.


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}" 
    />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜