【问题标题】:Adding dynamic properties to a class that is bound to UI in WPF app via DataTemplate (dynamic properties that are specific to an instance)通过 DataTemplate 将动态属性添加到绑定到 WPF 应用程序中的 UI 的类(特定于实例的动态属性)
【发布时间】:2021-05-22 12:47:12
【问题描述】:

我有一个 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 实例的动态属性。

然后我不确定如何编辑数据模板以以与现有属性类似的方式显示新添加的属性(如姓名和年龄)。

我不喜欢我的方法,也许你有更好的想法?谢谢!

【问题讨论】:

  • 嗨。我想为你制作一个样品。你能更简单准确地解释一下你想要什么吗?

标签: c# wpf reflection datatemplate dynamic-properties


【解决方案1】:

最终,我已经按照我在问题中建议的方式实现了它:

我已经添加到 person 类中:

public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }

然后在原始 DataTemplate 中使用了带有 itemTemplate 的附加 ItemsControl。

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2016-09-12
    • 2013-08-25
    • 1970-01-01
    • 2016-10-11
    • 2020-03-12
    • 2014-01-29
    • 2019-04-28
    相关资源
    最近更新 更多