编程语言
首页 > 编程语言> > c# – Wpf PropertyGrid Min / Max attrs

c# – Wpf PropertyGrid Min / Max attrs

作者:互联网

我正在使用WPF扩展工具包中的PropertyGrid来处理很多类型的对象.对象是配置的包装.许多属性都是整数,我想在类定义中定义具体属性的最小/最大范围.

像这样的东西:

    [Category("Basic")]
    [Range(1, 10)]
    [DisplayName("Number of outputs")]
    public int NumberOfOutputs
    {
        get { return _numberOfOutputs; }
        set 
        {
            _numberOfOutputs = value;
        }
    }

是否有一些解决办法?我认为使用PropertyGrid自定义编辑器是可能的,但我的意思是它不必要地复杂化.

非常感谢你!

解决方法:

您可以通过扩展PropertyGrid代码来实现此目的.

以下代码使用整数属性.

一步步:

1)从https://wpftoolkit.codeplex.com/SourceControl/latest下载源扩展WPF工具包.

2)将Xceed.Wpf.Toolkit项目添加到您的解决方案中.

3)在以下命名空间中添加RangeAttribute类:

namespace Xceed.Wpf.Toolkit.PropertyGrid.Implementation.Attributes
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class RangeAttribute : Attribute
    {
        public RangeAttribute(int min, int max)
        {
            Min = min;
            Max = max;
        }

        public int Min { get; private set; }
        public int Max { get; private set; }
    }
}

4)编辑ObjectContainerHelperBase类中的代码,将Min和Max值分配给appriopriate编辑器(IntegerUpDown).我发布了整个方法GenerateChildrenEditorElement,只需用以下代码替换此方法:

private FrameworkElement GenerateChildrenEditorElement( PropertyItem propertyItem )
{
  FrameworkElement editorElement = null;
  DescriptorPropertyDefinitionBase pd = propertyItem.DescriptorDefinition;
  object definitionKey = null;
  Type definitionKeyAsType = definitionKey as Type;

  ITypeEditor editor = pd.CreateAttributeEditor();
  if( editor != null )
    editorElement = editor.ResolveEditor( propertyItem );


  if( editorElement == null && definitionKey == null )
    editorElement = this.GenerateCustomEditingElement( propertyItem.PropertyDescriptor.Name, propertyItem );

  if( editorElement == null && definitionKeyAsType == null )
    editorElement = this.GenerateCustomEditingElement( propertyItem.PropertyType, propertyItem );

  if( editorElement == null )
  {
    if( pd.IsReadOnly )
      editor = new TextBlockEditor();

    // Fallback: Use a default type editor.
    if( editor == null )
    {
      editor = ( definitionKeyAsType != null )
      ? PropertyGridUtilities.CreateDefaultEditor( definitionKeyAsType, null )
      : pd.CreateDefaultEditor();         
    }

    Debug.Assert( editor != null );

    editorElement = editor.ResolveEditor( propertyItem );

      if(editorElement is IntegerUpDown)
      {
          var rangeAttribute = PropertyGridUtilities.GetAttribute<RangeAttribute>(propertyItem.DescriptorDefinition.PropertyDescriptor);
          if (rangeAttribute != null)
          {
              IntegerUpDown integerEditor = editorElement as IntegerUpDown;
              integerEditor.Minimum = rangeAttribute.Min;
              integerEditor.Maximum = rangeAttribute.Max;
          }
      }
  }

  return editorElement;
}

标签:c,wpf,propertygrid,wpf-extended-toolkit
来源: https://codeday.me/bug/20190624/1279925.html