【问题标题】:Generating TextBoxes to fill in a class生成文本框以填充类
【发布时间】:2015-03-21 05:04:46
【问题描述】:

我有几个类需要填写它们的属性。例如:

class RecordType1
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string Value { get; set;}
}

class RecordType2
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public float Temperature { get; set; }
}

对于 RecordType1,我想生成一个 DatePicker 来填写 Date 和两个 TextBox 来填写 NameValue。同样对于 RecordType2,我想要一个 DatePicker 和三个 TextBox 用于 Name,Location, andTemperature`。

我可以为每个类创建一个包含单独 UserControl 的文件,该文件具有所需的 TextBlocks 和 TextBoxes,但似乎有更好的方法来生成供用户填写的表单。

这种事情可能吗?

【问题讨论】:

  • 几分钟前我回答了一个非常相似的问题。看看here

标签: c# wpf mvvm


【解决方案1】:

在 WinForms 中执行此操作的一种快速而简单的方法是使用 PropertyGrid 控件。我不确定 WPF 中是否有等价物,但您可以使用 WindowsFormsHost 控制 host the PropertyGrid

【讨论】:

    【解决方案2】:

    它当然可能按照您的要求去做,即使在运行时也是如此。您将使用反射来获取各种字段,然后生成控件以匹配字段类型。

    现在,这不是一个非常实用的方法,尤其是考虑到这种生成表单的布局很可能很糟糕。通常的方法是手动创建表单/用户控件。

    由于您在 WPF 中,一个好的方法是使用数据模板而不是用户控件,因为您可以在 ItemsControls 和 ContentControls 中轻松使用它们

    【讨论】:

      【解决方案3】:

      可以通过反射来做到这一点。首先获取类型:

      Type typeinfo = typeof(RecordType1);
      

      然后您可以遍历属性。

      如果你不想自己做这一切,你可以使用超过属性网格。

      <UserControl x:Class="Interstone.Bestelbonnen.Views.DrawingPropertiesControl"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
               xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
               xmlns:vm="clr-namespace:Interstone.Bestelbonnen.ViewModels"
               xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
               mc:Ignorable="d" 
               d:DesignHeight="300" d:DesignWidth="300">
      <xctk:PropertyGrid SelectedObject="{Binding}" AutoGenerateProperties="False" IsCategorized="False">
      </xctk:PropertyGrid>           
      

      关于 propertygrid 的更多信息: http://wpftoolkit.codeplex.com/wikipage?title=PropertyGrid

      反射部分我没有过多阐述,不知道你想往哪个方向发展。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-21
        • 2017-04-27
        • 2016-02-20
        • 1970-01-01
        • 2015-11-05
        • 2012-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多