2017-08-11 87 views
0

我有一個Xamarin形式頁面,並在頁面上有一個靜態變量:如何更改靜態變量對Xamarin.Form進行更改?

namespace City 
{ 
    public static class MS 
    { 
     public static int secs; 
    } 
} 

我的XAML

<Label x:Name="secondsLabel" /> 

我的C#代碼更新這樣的

while () { 
    // the code updates the value of secs here in the loop 
    MS.secs++; 
    secondsLabel.Text = MS.secs.ToString(); 
} 

但價值在屏幕上不會改變。有沒有一種方法可以綁定到這個靜態整數,這樣當secs被C#代碼改變時,屏幕會自動更新?

回答

2
<Label x:Name="secondsLabel" Text="{Binding Source={x:Static local:MS.Secs}}" /> 

你只能綁定到公共屬性,所以你需要在後面的代碼或VM屬性

public static int Secs { 
    get { 
    return secs; 
    } 
    set { 
    secs = value; 
    PropertyChanged(); 
    } 
} 
+0

我需要有一個方法的PropertyChanged?此外,我不知道,但我的代碼是這樣做的:MS.secs ++;所以命名是否可以,或者我應該將代碼更改爲MS.Secs? – Melina

+1

你的類需要實現INotifyPropertyChanged。是的,你需要更新公共Secs屬性,因爲那是我們綁定的。 – Jason

+0

好吧,那麼你是不是說在MS中用大寫字母開頭的字段會更正常?我只是想做最受歡迎的事情。你可以在答案中提出一個PropertyChanged方法。我想確保我做對了。感謝 – Melina