2016-12-06 28 views
0

我有一個標籤label1,我試圖更新從單獨的類Server()的內容。如何從MainWindow類外部訪問標籤?

我曾嘗試通過主窗口()實例連接到我的服務器()類:

//MainWindow constrcutor 
Server.GetMainWindow(this); 


//Server() 
public static MainWindow mainWindow; 

GetMainWindow(MainWindow mw) 
{ 
     mainWindow = mw 
} 

這讓我看到了物業mainWindow.Label.Content,但我不「看」的變化,當我運行我的代碼。

我也嘗試過用這種方法。

public MainWindow() 
{ 
    Server.mainWindow = this; 
} 

但仍然是相同的結果。

我做錯了什麼?

回答

0

訪問您的主窗口中已經打開的情況下,最簡單的方法是使用Application.Current.Windows集合:

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>(); 
if (mainWindow != null) 
    mainWindow.Label.Content = "..."; 

這應該更新了X標籤的內容屬性:名稱「標籤「是在MainWindow的XAML標記中聲明的。