簡體   English   中英

自定義UserControl中的標簽內容未更新

[英]Label content in custom UserControl not updating

我創建了一個由12個標簽組成的自定義UserControl。

在此處輸入圖片說明

現在,在程序加載時,需要更改內容為“默認”的標簽。

// This is called in my main forms constructor, right before InitializeComponent()
public void ShowRigInfo()
{
    // This is here because if I try to call PopluateLabels, I get an "Object not
    // set to an instance of object" error
    grdRigInfo = new RigInfoGrid();

    var contractor = SplitString("contractor", _rigInfo);
    var projectName = SplitString("projectname", _rigInfo);
    var location = SplitString("location", _rigInfo);
    var operatorName = SplitString("operator", _rigInfo);
    var rigName = SplitString("rigsite_name", _rigInfo);
    var rigManager = SplitString("rigmanager", _rigInfo);

    grdRigInfo.PopulateLabels(contractor, projectName, location, operatorName,
                              rigName, rigManager);
    }

// A public method of my custom UserControl to update label content
public void PopulateLabels(string contractor, string project, string location, 
                           string operatorName, string rigName, string manager)
{
    lblContractor.Content = contractor;
    lblProjectName.Content = project;
    lblLocation.Content = location;
    lblOperator.Content = operatorName;
    lblRigName.Content = rigName;
    lblRigManager.Content = manager;            
}

我的問題是,如何在程序啟動時更新標簽? 感謝您提供的所有幫助。

編輯

我試圖在我的主窗體的InitializeComponent()之前和之后調用ShowRigInfo() 他們倆都沒有更改標簽。

編輯2

好吧,我在實際看到答案之前就解決了這個問題。 我所做的是將ShowRigInfo()移到了自定義UserControl中,而不是我的主窗體中。 我不知道為什么我從一開始就沒有這樣做,但是確實如此。 我將研究答案的DataBinding部分。 感謝大伙們。

好吧,因為這是WPF,所以我建議將這些標簽綁定到支持(實現)INotifyPropertyChanged的某種模型中的屬性。

如果您用這些話來Google,您將會走很長一段路。

為什么不在Loaded事件處理程序中嘗試呢?

AD.Net是正確的:將您的初始設置放入Loaded事件。 在構造函數中,您可以使用局部變量,但是通常不能使用視覺元素。 觸發“已加載”事件后,您的所有UI組件都應該可以使用。

但是,我強烈建議您在Labels上使用DataBinding和DataContext,而不要通過公共方法來填充它們。 最終,如果您開始使用數據網格,樹視圖和列表視圖,您將了解WPF系統是如何圍繞綁定構建的。

暫無
暫無

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

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