我将 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
中的代码以将最小值和最大值分配给适当的编辑器 (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 最小/最大属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970907/