Поделиться через


NotifyParentPropertyAttribute Класс

Определение

Указывает, что родительское свойство уведомляется при изменении значения свойства, к которому применяется этот атрибут. Этот класс не может быть унаследован.

public ref class NotifyParentPropertyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Property)]
public sealed class NotifyParentPropertyAttribute : Attribute
public sealed class NotifyParentPropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Property)>]
type NotifyParentPropertyAttribute = class
    inherit Attribute
type NotifyParentPropertyAttribute = class
    inherit Attribute
Public NotInheritable Class NotifyParentPropertyAttribute
Inherits Attribute
Наследование
NotifyParentPropertyAttribute
Атрибуты

Примеры

В следующем примере кода показано, как использовать NotifyParentPropertyAttributeExpandableObjectConverter и класс для создания расширяемого свойства в пользовательском элементе управления.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;

namespace ExpandableObjectDemo;

public partial class DemoControl : UserControl
{
    Container components;

    public DemoControl() => InitializeComponent();

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [Category("Demo")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public BorderAppearance Border { get; set; } = new();

    void InitializeComponent()
    {
        components = new Container();
        AutoScaleMode = AutoScaleMode.Font;
    }
}

[TypeConverter(typeof(BorderAppearanceConverter))]
public class BorderAppearance
{
    int borderSizeValue = 1;
    Color borderColorValue = Color.Empty;

    [Browsable(true),
    NotifyParentProperty(true),
    EditorBrowsable(EditorBrowsableState.Always),
    DefaultValue(1)]
    public int BorderSize
    {
        get => borderSizeValue;
        set
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException(
                    "BorderSize",
                    value,
                    "must be >= 0");
            }

            if (borderSizeValue != value)
            {
                borderSizeValue = value;
            }
        }
    }

    [Browsable(true)]
    [NotifyParentProperty(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [DefaultValue(typeof(Color), "")]
    public Color BorderColor
    {
        get => borderColorValue;
        set
        {
            if (value.Equals(Color.Transparent))
            {
                throw new NotSupportedException("Transparent colors are not supported.");
            }

            if (borderColorValue != value)
            {
                borderColorValue = value;
            }
        }
    }
}

public class BorderAppearanceConverter : ExpandableObjectConverter
{
    // This override prevents the PropertyGrid from 
    // displaying the full type name in the value cell.
    public override object ConvertTo(
        ITypeDescriptorContext context,
        CultureInfo culture,
        object value,
        Type destinationType) => destinationType == typeof(string)
            ? ""
            : base.ConvertTo(
            context,
            culture,
            value,
            destinationType);
}
Imports System.ComponentModel
Imports System.Drawing
Imports System.Globalization
Imports System.Windows.Forms

Public Class DemoControl
    Inherits UserControl

    Private borderAppearanceValue As New BorderAppearance()
    Private components As System.ComponentModel.IContainer = Nothing


    Public Sub New()
        InitializeComponent()

    End Sub

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)

        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If

        MyBase.Dispose(disposing)

    End Sub

    <Browsable(True), _
    EditorBrowsable(EditorBrowsableState.Always), _
    Category("Demo"), _
    DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
    Public Property Border() As BorderAppearance

        Get
            Return Me.borderAppearanceValue
        End Get

        Set(ByVal value As BorderAppearance)
            Me.borderAppearanceValue = value
        End Set

    End Property

    Private Sub InitializeComponent()
        components = New System.ComponentModel.Container()
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font

    End Sub
End Class

<TypeConverter(GetType(BorderAppearanceConverter))>  _
Public Class BorderAppearance
    Private borderSizeValue As Integer = 1
    Private borderColorValue As Color = Color.Empty
    
    
    <Browsable(True), NotifyParentProperty(True), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(1)>  _
    Public Property BorderSize() As Integer 
        Get
            Return borderSizeValue
        End Get
        Set
            If value < 0 Then
                Throw New ArgumentOutOfRangeException("BorderSize", value, "must be >= 0")
            End If
            
            If borderSizeValue <> value Then
                borderSizeValue = value
            End If
        End Set
    End Property
    
    
    <Browsable(True), NotifyParentProperty(True), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(GetType(Color), "")>  _
    Public Property BorderColor() As Color 
        Get
            Return borderColorValue
        End Get
        Set
            If value.Equals(Color.Transparent) Then
                Throw New NotSupportedException("Transparent colors are not supported.")
            End If
            
            If borderColorValue <> value Then
                borderColorValue = value
            End If
        End Set
    End Property
End Class

Public Class BorderAppearanceConverter
    Inherits ExpandableObjectConverter
    
    ' This override prevents the PropertyGrid from 
    ' displaying the full type name in the value cell.
    Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object

        If destinationType Is GetType(String) Then
            Return ""
        End If

        Return MyBase.ConvertTo(context, culture, value, destinationType)

    End Function
End Class

Комментарии

Применяется NotifyParentPropertyAttribute к свойству, если его родительское свойство должно получать уведомление об изменениях значений свойства. Например, в окне "Свойства" DataGridView.RowTemplate свойство имеет вложенные свойства, такие как Height и DefaultCellStyle. Эти вложенные свойства помечены так NotifyParentPropertyAttribute(true) , что они уведомляют родительское свойство об обновлении его значения и отображаются при изменении значений свойств.

Дополнительные сведения об использовании атрибутов см. в разделе "Атрибуты".

Конструкторы

Имя Описание
NotifyParentPropertyAttribute(Boolean)

Инициализирует новый экземпляр NotifyParentPropertyAttribute класса, используя указанное значение, чтобы определить, уведомляется ли родительское свойство об изменениях значения свойства.

Поля

Имя Описание
Default

Указывает состояние атрибута по умолчанию, что свойство не должно уведомлять родительское свойство об изменениях его значения. Это поле доступно только для чтения.

No

Указывает, что родительское свойство не уведомляется об изменениях значения свойства. Это поле доступно только для чтения.

Yes

Указывает, что родительское свойство уведомляется об изменениях значения свойства. Это поле доступно только для чтения.

Свойства

Имя Описание
NotifyParent

Возвращает или задает значение, указывающее, должно ли родительское свойство получать уведомления об изменениях значения свойства.

TypeId

При реализации в производном классе получает уникальный идентификатор для этого Attribute.

(Унаследовано от Attribute)

Методы

Имя Описание
Equals(Object)

Возвращает значение, указывающее, совпадает ли указанный объект с текущим объектом.

GetHashCode()

Возвращает хэш-код для этого объекта.

GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

Возвращает значение, указывающее, является ли текущее значение атрибута значением по умолчанию для атрибута.

Match(Object)

При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от Attribute)

Применяется к

См. также раздел