簡體   English   中英

從自定義控件的另一個屬性獲取設計器中設置的屬性值

[英]Get the property value set in the Designer from another property of a Custom Control

我制作了自定義控件,並添加了一個指向資源的新屬性。
如何從自定義控件的另一個屬性獲取在表單設計器中設置的此屬性的值? 當我嘗試讀取它時,它返回的值為null

在此處輸入圖片說明

我的代碼與自定義控件和提到的屬性相關:

class ResourceLabel : Label
{
    private string resourceKey;
    
    [Category("Appearance")]
    [Browsable(true)]
    [Description("Sets the resource key for localization")]
    public string ResourceKey
    {
        get { return resourceKey; }
        set {
            if (resourceKey != value) {
                resourceKey = value;
                Invalidate();
            }
        }
    }

    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [Bindable(true)]
    public override string Text
    {
        if (base.Text != value) {
            Console.WriteLine($"Test: {ResourceKey}");

            if (ResourceKey != null) {
                var locale = CultureInfo.GetCultureInfo(Properties.Settings.Default.Language);
                var textFromResource = Resources.ResourceManager.GetString(ResourceKey, locale);
                base.Text = textFromResource;
            } 
            else {
                base.Text = value;
            }
        }
    }
}

這個字符串Console.WriteLine($"Test: {ResourceKey}"); 返回null

鑒於問題的Description和應用於自定義控件的ResourceKey屬性的Description屬性,您似乎正在本地化您的應用程序,因此將父 Form 的Localizable屬性設置為true

這會更改表單初始化中的一些細節。
如果您查看 Form.Designer.cs 文件,您會注意到添加了一些新部分:
通常:
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(YourForm));

現在有了新的同伴。 在每個控件的初始化部分, resources.ApplyResources(this.controlName, "controlName"); 已添加。

您的自定義標簽應顯示,例如:

resources.ApplyResources(this.resourceLabel1, "resourceLabel1");

許多從Control派生的標准屬性都是可本地化的(用[Localizable(true)]屬性修飾)。 Text 屬性當然是其中之一 這些屬性的值現在存儲在用於不同本地化的資源文件中。 因此,這些屬性不再在 Designer.cs 文件中設置,並且在其他屬性之前初始化。

您的ResourceKey屬性未定義為Localizable ,因此它被添加到 Designer.cs 文件中並在本地化屬性之后初始化。

▶ 一個簡單的解決方法是將ResourceKey屬性定義為Localizable ,因此它將在非本地化屬性以及Text屬性之前初始化。

[Localizable(true), Browsable(true)]
[Category("Appearance"), Description("Sets the resource key for localization")]
public string ResourceKey {
    get { return resourceKey; }
    set {
        if (resourceKey != value) {
            resourceKey = value;
            Invalidate();
        }
    }
}

請注意,這在某種程度上是一個重大變化,您應該:

1 - 將Localizable屬性添加到ResourceKey屬性
2 - 從表單設計器中刪除舊的ResourceLabel控件
3 - 編譯解決方案
4 - 將自定義ResourceLabel添加回原來的位置
5 - 在屬性面板中設置所需控件的屬性
6 - 運行應用程序或編譯項目

檢查您的 Form 的 Designer.cs 文件,看到ResourceKey屬性已經消失,它的值現在通過resources.ApplyResource()設置。

▶ 如果不想使該屬性可本地化,則必須稍后在 Control 初始化完成時讀取其值; 例如,覆蓋OnHandleCreated 請注意,在少數情況下,可以在運行時重新創建控件的句柄(設置需要控件重新創建句柄的關鍵屬性)。

注意
你不應該依賴你的屬性的初始化順序,沒有真正保證一個屬性在另一個之前初始化。 在設計控件的行為時要考慮到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM