问题描述
我有一个 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 int Age { set; get; }
}
在我的视图模型中,我有一个
public ObservableCollection<Person> People { get; set; }
我的视图如下所示:
<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>
运行应用程序时,我们得到:
现在,要求是在单击“添加新属性”按钮后,将打开一个弹出窗口,用户将在其中填写“属性名称”、“属性类型”和“属性值”。一旦用户在弹出窗口中单击“应用”,我们将返回到显示的视图,新属性应添加到数据模板中。例如,如果用户在弹出窗口中填写了 Adam:
物业名称:职业
属性类型:字符串
属性值:“老师”
然后,点击弹出窗口中的应用按钮,我们将得到:
请注意,它就像一个属性:
public string Occupation { 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; }
这将代表特定于类 person 实例的动态属性。
然后我不知道如何编辑数据模板来以与现有属性类似的方式(如姓名和年龄)显示新添加的属性。
我不喜欢我的方法,也许您有更好的想法?谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)