【问题标题】:Generating an entry form from a Dictionary<String,Type>从 Dictionary<String,Type> 生成条目表单
【发布时间】:2015-05-03 09:49:18
【问题描述】:

我正在构建一个插件系统,我希望它尽可能动态 - 因此,我也想要一个设置面板。为此,我将从字典创建设置页面,其中 TKey 定义参数的标签,而 TValue 定义参数的类型。但是我还没有找到一种简单的方法来生成实际的 UI。我不想做太多,它会是一个简单的 StackPanel,带有一个预定义的 TextBlock-TextBox 对 - 每一个都代表一个 Dictionary 条目。

如何以简单的方式做到这一点?

【问题讨论】:

    标签: c# wpf user-interface dynamic-usercontrols dynamic-ui


    【解决方案1】:

    Dictionary 不是最佳绑定,因为它返回的 KeyValuePair 是不可变的(因此不能用于双向绑定)。

    如果您仍想将数据保存在字典中,可以将其包装在包含键的类中(以便在TextBlock 中显示一些内容)。一种方法:

    // some classes to represent our settings
    public abstract class Parameter
    {
        public string Key { get; private set; }
        public Parameter( string key ) { this.Key = key; }
    }
    
    public class StringParameter : Parameter
    {
        public string Value { get; set; }
        public StringParameter( string key, string value ) : base( key )
        {
            this.Value = value;
        }
    }
    

    一些测试数据:

    public Dictionary<string, Parameter> m_Settings = new Dictionary<string, Parameter>();
    // NOTE: we're returning the dictionary values here only
    public IEnumerable<Parameter> Settings { get { return m_Settings.Values; } }
    
    ...
    
    var p1 = new StringParameter( "Parameter 1", "Value 1" );
    var p2 = new StringParameter( "Parameter 2", "Value 2" );
    var p3 = new StringParameter( "Parameter 3", "Value 3" );
    
    m_Settings.Add( p1.Key, p1 );
    m_Settings.Add( p2.Key, p2 );
    m_Settings.Add( p3.Key, p3 );
    

    还有一个非常简单的用户界面:

    <Window ...
            xmlns:self="clr-namespace:WpfApplication8"
            DataContext="{Binding RelativeSource={RelativeSource Self}}" >
        <ItemsControl ItemsSource="{Binding Settings}">
            <ItemsControl.Resources>
                <DataTemplate DataType="{x:Type self:StringParameter}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Key}"/>
                        <TextBox Text="{Binding Value, Mode=TwoWay}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.Resources>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>            
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Window>
    

    拥有通用基础Parameter 允许您拥有不同类型的设置,所有设置都有自己的DataTemplate。请注意,所有这些都缺乏任何验证以及您需要的所有东西。

    【讨论】:

    • 正如您可能从我的示例中看到的那样,我不打算将设置保存到 Dictionary 本身,我只是将其用于字段的描述(名称和类型)。实际设置将单独存储。
    • 我明白了。好吧,然后跳过字典并绑定到描述设置的类列表(正如我所做的那样)。然后当用户完成后,只需从列表中获取值。您显然可以生成老式的 UI,但由于您使用的是 WPF 绑定,所以要走的路。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2021-10-04
    • 2012-09-21
    相关资源
    最近更新 更多