【问题标题】:What is the easiest way to display the Properties of the Model as Label and Textbox?将模型的属性显示为标签和文本框的最简单方法是什么?
【发布时间】:2019-07-06 13:22:46
【问题描述】:

我正在使用带有 WPF 的 MVVM 模式,并且我确实希望在标签和文本框列表的视图中显示模型中的所有属性。因此,属性的名称应该在标签中,并且属性的值应该具有与文本框的绑定。 (见下图)

本例中的模型有以下属性:(当然有 PropertyChanged)

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

到目前为止,我确实认为:

<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>

有没有一种简单的方法可以从模型中获取这样的视图?在我的例子中,模型有 30 个属性,如果添加或更改属性,也许有一种更简单的方法来代替更改 UI。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    你可以试试这个 detailsview 控件。 https://archive.codeplex.com/?p=wpfdetailsview

    【讨论】:

      【解决方案2】:

      您可以使用Extended WPF Toolkit 中的PropertyGrid 控件:

      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>
      

      【讨论】:

        【解决方案3】:

        使用反射:

        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);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-23
          • 2010-12-11
          • 1970-01-01
          • 2013-12-30
          • 1970-01-01
          • 1970-01-01
          • 2018-05-22
          相关资源
          最近更新 更多