2012-10-26 85 views
2

我創建了一個由12個標籤組成的自定義UserControl。自定義UserControl中的標籤內容未更新

enter image description here

現在,當程序加載,以「默認」爲內容的標籤需要改變。

// 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()。他們都沒有改變標籤。

EDIT 2

好吧,我解決了這個之前,我居然看到了答案。我所做的是將我的ShowRigInfo()移動到我的自定義UserControl中,而不是我的主窗體。我不知道爲什麼我從一開始就沒有這樣做,但現在就是這樣。我將研究答案的DataBinding部分。感謝你們。

+0

爲什麼你不把它放在InitializeComponent()之後? – Davio

+0

@Davio:我已經試過了,它也沒有改變任何東西。 – MyCodeSucks

+0

@Prayos我發現你的問題說你在* InitializeComponent()之前試過*。你嘗試過嗎?您的標籤需要進行初始化,然後才能對其進行編輯 – Rachel

回答

3

好,因爲這是WPF,我會建議在某種模式的支持(實現)這些標籤綁定的屬性INotifyPropertyChanged的。

如果你用谷歌這些詞,你會走很長的路。

2

爲什麼不試試呢在Loaded事件處理

1

AD.Net正確:將您的初始設置放入Loaded事件中。在構造函數中,你可以玩局部變量,但你通常不能玩視覺元素。一旦「Loaded」事件被觸發,所有的UI組件都應該可以使用。

但是,我強烈建議您在標籤上使用DataBinding和DataContext,而不是通過公共方法填充它們。最後,如果您開始使用數據網格,樹視圖和列表視圖,您將意識到WPF系統是如何圍繞Binding構建的。

相關問題