2014-02-23 20 views
4

我正在使用PropertyGrid從WPF擴展工具包的很多類型的對象。對象是configs的包裝。許多屬性都是整數,我想在類定義中定義具體屬性的最小/最大範圍。Wpf PropertyGrid最小/最大值attrs

事情是這樣的:

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

有一些解決方案才達到的?我認爲這是可能的PropertyGrid的自定義編輯器,但我的意思是它過於複雜。

非常感謝!

+0

請詳細說明:「我要定義在類定義具體屬性的最小/最大範圍」 –

+1

我的意思是我想用混凝土property屬性它定義的屬性的最小/最大值。 – Frk

回答

4

您可以通過擴展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類編緝代碼分配最小值和最大值,以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; 
} 
+0

非常感謝... – Frk