NotifyParentPropertyAttribute Classe

Definição

Indica que a propriedade principal é notificada quando o valor da propriedade a que este atributo é aplicado é modificado. Esta classe não pode ser herdada.

public ref class NotifyParentPropertyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Property)]
public sealed class NotifyParentPropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Property)>]
type NotifyParentPropertyAttribute = class
    inherit Attribute
Public NotInheritable Class NotifyParentPropertyAttribute
Inherits Attribute
Herança
NotifyParentPropertyAttribute
Atributos

Exemplos

O exemplo de código seguinte demonstra como usar a NotifyParentPropertyAttribute classe e ExpandableObjectConverter para criar uma propriedade expansível num controlo personalizado.

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

Observações

Candidate-se NotifyParentPropertyAttribute a um imóvel se a sua propriedade principal receber notificação de alterações nos valores do imóvel. Por exemplo, no janela Propriedades, a propriedade DataGridView.RowTemplate tem propriedades aninhadas como Height e DefaultCellStyle. Estas propriedades aninhadas são marcadas com NotifyParentPropertyAttribute(true) para notificarem a propriedade principal para atualizar o seu valor e mostrarem quando os valores das propriedades mudarem.

Para mais informações sobre o uso de atributos, consulte Atributos.

Construtores

Name Description
NotifyParentPropertyAttribute(Boolean)

Inicializa uma nova instância da NotifyParentPropertyAttribute classe, usando o valor especificado para determinar se a propriedade pai é notificada de alterações no valor da propriedade.

Campos

Name Description
Default

Indica o estado do atributo padrão, que indica que a propriedade não deve notificar a propriedade principal das alterações ao seu valor. Este campo é só de leitura.

No

Indica que a propriedade principal não deve ser notificada de alterações no valor da propriedade. Este campo é só de leitura.

Yes

Indica que a propriedade principal foi notificada de alterações no valor da propriedade. Este campo é só de leitura.

Propriedades

Name Description
NotifyParent

Recebe ou define um valor que indica se a propriedade principal deve ser notificada de alterações no valor da propriedade.

TypeId

Quando implementado numa classe derivada, obtém um identificador único para esta Attribute.

(Herdado de Attribute)

Métodos

Name Description
Equals(Object)

Recebe um valor que indica se o objeto especificado é igual ao objeto atual.

GetHashCode()

Obtém o código hash deste objeto.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Recebe um valor que indica se o valor atual do atributo é o valor padrão do atributo.

Match(Object)

Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

Name Description
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Ver também