I have a WPF application. I have A Person Class that looks as following:
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; }
}
In my view model, I have an
public ObservableCollection<Person> People { get; set; }
And my View looks as following:
<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>
When running the app, we get:
Now, the requirement is that upon clicking on the Add New Property button, a pop up will open, and there the user will fill in the Property name, Property type and Property Value. Once the user clicks "Apply" at the popup, we are back to the shown view, and the new property should be added to data template. For example, if the user has filled in at the popup for Adam:
Property name: occupation
Property type: string
Property value: "Teacher"
Then, upon clicking on the Apply button at the popup, we will get:
Note that it's like a property of:
public string Occupation { get; set; }
was added to the Person class, but only to the first instance of Adam.
I have a few ideas, but what is the best approach for implementing something like this?
I think about declaring a model class called DynamicProperty:
public class DynamicProperty
{
public string Name { set; get; }
public Type Type { set; get; }
public object Value { set; get; }
}
Then, I would add to the person class:
public ObservableCollection<DynamicProperty> DynamicProperties { get; set; }
This would represent the dynamic properties that as I've mentioned that are specific to an instance of class person.
Then I'm not sure how to edit the data Template to display the newly added properties in a similar way to the existing one (like Name & Age).
I don't like something about my approach, maybe you have any better ideas? Thank you!
Aucun commentaire:
Enregistrer un commentaire