DmitryB
DmitryB

Reputation: 525

C# WinForms. Implementing the property "Name" in the component

I would like to implement property Name in the Component that would have the same value as the name of a field in the Form that point to the component.

 private MyComponent myComponent1;
 this.myComponent1.Name = "myComponent1";

WinForms already implement such a property in Control class, but I can't understand how it works.

 private System.Windows.Forms.Button button1;
 this.button1.Name = "button1";

I think about declaring private string Name property in the MyComponentDesigner. Or using ComponentRename event in the IComponentChangeService service. Exploring source code of WinForms does not give an exact explanation.

Upvotes: 3

Views: 1819

Answers (2)

Steve Mol
Steve Mol

Reputation: 153

For others (like me) that prefer VB, here's the code:

Private _name As String
<Browsable(False)>
Public Property Name As String
    Get
        If Site IsNot Nothing Then _name = Site.Name
        Return _name
    End Get
    Set(ByVal value As String)
        If Site IsNot Nothing Then Site.Name = value
        _name = value
    End Set
End Property

Now, I added one more line so that calls for the Name that may occur very early -- before the name has been set -- don't get an empty response. Here's my code:

Private _name As String
<Browsable(False)>
Public Property Name As String
    Get
        If Site IsNot Nothing Then
            _name = Site.Name
            If _name = String.Empty Then Return ToString()
        End If
        Return _name
    End Get
    Set(ByVal value As String)
        If Site IsNot Nothing Then Site.Name = value
        _name = value
    End Set
End Property

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125257

If you just want a simple Name property that shows in property grid, it's enough to add a trivial automatic get-set Name property to your component. But if you want your component have Name property and the (Name) property act like (Name) property of controls add the Name property this way:

string name;
[Browsable(false)]
public string Name
{
    get
    {
        if (Site != null)
            name = Site.Name;
        return name;
    }
    set
    {
        if (Site != null)
            Site.Name = value;
        name = value;
    }
} 

This way, you can get or set the Name property using code, or in property grid. In property grid, when you assign a value to (Name) it will assign the Name property and the designer generates the component name assignment as well.

Upvotes: 3

Related Questions