C# 向通过DataTemplate绑定到WPF应用程序中UI的类添加动态属性(特定于实例的动态属性)
我有一个WPF应用程序。我有一个Person类,如下所示:C# 向通过DataTemplate绑定到WPF应用程序中UI的类添加动态属性(特定于实例的动态属性),c#,wpf,reflection,datatemplate,dynamic-properties,C#,Wpf,Reflection,Datatemplate,Dynamic Properties,我有一个WPF应用程序。我有一个Person类,如下所示: public class Person { public Person(string id, string name, int age) { Id = id; Name = name; Age = age; } public string Id { set; get; } public string Name { set; get; }
public class Person
{
public Person(string id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public string Id { set; get; }
public string Name { set; get; }
public int Age { set; get; }
}
<Grid>
<ItemsControl x:Name="DynamicPeople" ItemsSource="{Binding Path=People}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="Gray" Margin="6">
<StackPanel Orientation="Horizontal">
<Label Content="Id"/>
<Label Content="{Binding Path=Id}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Name"/>
<Label Content="{Binding Path=Name}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Age"/>
<Label Content="{Binding Path=Age}"/>
</StackPanel>
<Button Width="120" Height="60">Add New Property</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
在我的视图模型中,我有一个
public ObservableCollection<Person> People { get; set; }
已添加到Person类,但仅添加到Adam的第一个实例
我有一些想法,但是实现这样的东西的最佳方法是什么
我考虑声明一个名为DynamicProperty的模型类:
public class DynamicProperty
{
public string Name { set; get; }
public Type Type { set; get; }
public object Value { set; get; }
}
然后,我将向person类添加:
public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }
public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }
publicobservableCollection动态属性{get;set;}
这将表示动态属性,正如我所提到的,这些属性特定于类person的实例
然后,我不确定如何编辑数据模板,以与现有属性类似的方式显示新添加的属性(如名称和年龄)
我不喜欢我的方法,也许你有更好的主意?谢谢大家! 最终,我实现了类似于我在问题中提出的建议: 我已将以下内容添加到person类中:
public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }
public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }
publicobservableCollection动态属性{get;set;}
然后在原始数据模板的内部使用了一个附加的ItemsControl和itemTemplate。Hi。我想给你做个样品。你能更简单准确地解释你想要什么吗?