You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Extended WPF Toolkit的PropertyGrid中无XAML实现多行字符串输入?

实现Extended WPF Toolkit PropertyGrid的多行字符串输入(无XAML模板)

嘿,我刚好做过类似的实现,完全满足你不想写XAML编辑模板、靠属性标记搞定的需求!其实Extended WPF Toolkit的PropertyGrid支持通过自定义编辑器+属性标记的方式实现,和WinForms PropertyGrid的思路很像,下面是具体步骤和代码:

1. 自定义多行文本编辑器

首先我们要实现一个针对多行文本的TypeEditor,它会告诉PropertyGrid用多行TextBox来渲染指定属性:

using Xceed.Wpf.Toolkit.PropertyGrid.Editors;
using System.Windows.Controls;

public class MultiLineTextEditor : TypeEditor<TextBox>
{
    // 创建多行TextBox控件
    protected override TextBox CreateEditor()
    {
        return new TextBox
        {
            AcceptsReturn = true, // 允许回车换行
            TextWrapping = System.Windows.TextWrapping.Wrap, // 自动换行
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto, // 自动显示垂直滚动条
            MinHeight = 80, // 设置最小高度,提升输入体验
            Margin = new System.Windows.Thickness(2) // 加个内边距,视觉更舒服
        };
    }

    // 指定绑定的依赖属性(TextBox的Text属性)
    protected override void SetValueDependencyProperty()
    {
        ValueProperty = TextBox.TextProperty;
    }
}

2. 用属性标记需要多行输入的字段

为了让代码更简洁,我们可以封装一个自定义属性,替代冗长的EditorAttribute:

using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

public class MultiLineTextAttribute : EditorAttribute
{
    public MultiLineTextAttribute()
        : base(typeof(MultiLineTextEditor), typeof(PropertyEditor))
    {
    }
}

之后在你的数据对象的字符串属性上,直接标记这个属性就可以了:

public class YourDataModel
{
    // 普通单行文本属性
    public string SingleLineContent { get; set; } = "这是默认的单行文本";

    // 需要多行输入的属性,只需加一个标记
    [MultiLineText]
    public string MultiLineContent { get; set; } = "第一行内容\n第二行内容\n第三行内容";
}

3. 绑定到PropertyGrid

最后把你的数据对象绑定到PropertyGrid,MultiLineContent属性就会自动渲染成多行文本框,完全不需要写任何XAML编辑模板!

小提示:如果不需要封装自定义属性,也可以直接用原生的EditorAttribute标记,效果是一样的:

[Editor(typeof(MultiLineTextEditor), typeof(PropertyEditor))]
public string MultiLineContent { get; set; }

这种方式和WinForms里靠属性实现多行输入的逻辑一致,只需要在数据类上做标记,非常方便。

内容的提问来源于stack exchange,提问作者Amen Jlili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:25:28