我有一个列表框,我已将数据上下文绑定到一个对象。这个对象有许多属性,其中一些属性会有特定的属性。WPF绑定到具有特定属性的对象的属性
我想从中做的是将项目源设置为对象的属性,但仅显示具有特定属性集的属性。
任何人都可以帮助我从哪里开始呢?
我有一个列表框,我已将数据上下文绑定到一个对象。这个对象有许多属性,其中一些属性会有特定的属性。WPF绑定到具有特定属性的对象的属性
我想从中做的是将项目源设置为对象的属性,但仅显示具有特定属性集的属性。
任何人都可以帮助我从哪里开始呢?
你可以使用LINQ和反射来获取具有该属性的值属性集:
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);
在我的测试中名称和DOB被标记为[Att],并且它们的值被添加到列表框中。 SSN不是。
一种方法是构建数据上下文object dynamically并将Visibility属性绑定到此动态构建对象上的属性。然后,您可以通过以下方式来使用它:
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();
在视图中,您现在可以执行以下操作:
<TextBlock
Visibility="{Binding PropertyWithAttributeVisibility}"
Text="{Binding PropertyWithAttribute}"
/>