简体   繁体   中英

What is the easiest way to display the Properties of the Model as Label and Textbox?

I am using the MVVM pattern with WPF and I do want to show all properties from the model in the View in a list of labels and textboxes. So the name of the property should be in a label and the value of the property should have a Binding to a Textbox. (See image below)

标签和文本框

The model in this example has following properties: (of course with PropertyChanged)

public class HoseData
{
    public string Article {get; set;} = "6931313"
    public string Description {get; set;} = ""
    public string Type {get; set;} = "DKC"
}

Until now i do have this in my view:

<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Article" />
        <TextBox Text="{Binding Article}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Description" />
        <TextBox Text="{Binding Description}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Content="Type" />
        <TextBox Text="{Binding Type}" />
    </StackPanel>
</StackPanel>

Is there an easy way to get such a View out of the Model? In my case the Model has 30 properties and maybe there is an easier way instead of changing the UI if a property is added or changed.

Use Reflection:

var hd = new HoseData();

...

PropertyInfo[] properties = typeof(HoseData).GetProperties();
foreach (PropertyInfo pi in properties)
{
    var name = pi.Name;
    var value = pi.GetValue(hd);
    var label = new Label()
    {
        Content = name
    };
    var textbox = new TextBox()
    {
        Text = value.ToString(),
    };
    var binding = new Binding(name)
    {
        Source = hd,
        Mode = BindingMode.TwoWay,
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
    };
    textbox.SetBinding(TextBox.TextProperty, binding);
    var stackpanel = new StackPanel()
    {
        Orientation = Orientation.Horizontal
    };
    stackpanel.Children.Add(label);
    stackpanel.Children.Add(textbox);
    sp.Children.Add(yourMainStackPanel);
}

You could use the PropertyGrid control from the Extended WPF Toolkit :

xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
...
<xctk:PropertyGrid ShowSearchBox="False" ShowTitle="False" ShowSummary="False" ShowAdvancedOptions="False"
                   ShowSortOptions="False">
    <xctk:PropertyGrid.SelectedObject>
        <local:HoseData />
    </xctk:PropertyGrid.SelectedObject>
</xctk:PropertyGrid>

You could try this detailsview control. https://archive.codeplex.com/?p=wpfdetailsview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM