Yiannis Mpourkelis
Yiannis Mpourkelis

Reputation: 1386

How can I create a localizable UserControl?

For simplicity, I have a UserControl with a Label on it and I want the label text to be localizable. Inside the UserControl I created a public LabelText property to get/set the label text.

This is the code of my UserControl

Imports System.ComponentModel

Public Class ctlA

    <Browsable(True), _
    EditorBrowsable(EditorBrowsableState.Always), _
    Localizable(True), _
    DefaultValue("dafaultLabel"), _
    DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
    Private _LabelText As String = "label"
    Public Property LabelText() As String
        Get
            Return _LabelText
        End Get
        Set(ByVal value As String)
            _LabelText = value
            Label1.Text = value
        End Set
    End Property
End Class

I can insert the UserControl to a form, but I can not localize the LabelText property when I choose a different language for my form.

What should I do to make the LabelText property localizable?

Upvotes: 1

Views: 2159

Answers (2)

Yiannis Mpourkelis
Yiannis Mpourkelis

Reputation: 1386

I will answer my question after hours of trial and error.

  1. Only the Localizable attribute is required.
  2. The declariation of private property fields should go above the attributes.

The working code that supports UserControl localization is this:

Imports System.ComponentModel

Public Class ctlA

    Private _LabelText As String = "label"
    <Localizable(True)>
    Public Property LabelText() As String
        Get
            Return _LabelText
        End Get
        Set(ByVal value As String)
            _LabelText = value
            Label1.Text = value
        End Set
    End Property
End Class

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244752

You localize a UserControl in the exact same way that you localize a Form. You set the Localizable property to true, and specify a language. The localization happens at runtime. A walkthrough of the process is available here.

As far as making custom properties localizable, you have already done the right thing by adding the Localizable attribute to their definition.

The problem here is that a UserControl on a form is treated independently of the container form. It doesn't inherit the localization settings of the form, you have to set the UserControl separately.

Upvotes: 1

Related Questions