2017-07-17 109 views
1

這是我的嘗試。改變構造函數的作品,但我似乎無法動態改變。如何動態更改Xamarin C#中標籤文本的顏色?

public PhrasesFrame() 
    { 
     InitializeComponent(); 
     correctButton.Clicked += correctButtonClicked; 
     resetButton.Clicked += resetButtonClicked; 
     faveLabel.BackgroundColor = Color.Red; 
     faveLabel.GestureRecognizers.Add(new TapGestureRecognizer 
     { 
      Command = new Command(() => FaveLabelTapped()) 
     }); 
     // this works 
     faveLabel.TextColor = Color.Red; 

    } 

    void FaveLabelTapped() 
    { 
     AS.phrase.Favorite = !AS.phrase.Favorite; 
     if (AS.phrase.Favorite) { 
      // this gives an error 
      faveLabel.TextColor = Color.Red; 
     } else { 
      faveLabel.TextColor = Color.Yello; 
     } 
     App.DB.UpdateFavorite(AS.phrase.Favorite, AS.phrase.PhraseId); 
    } 

給我留言

顏色沒有出現在目前的情況下存在

有人可以給我一些建議,我怎麼可以從FaveLabelTapped方法內部改變?

+0

您可能需要使用此 – Jimbot

+0

結合有一個簡單的方法,我可以做到這一點綁定?我的方式似乎很容易,如果它在另一種方法工作。 – Alan2

+0

您是否包含了'Xamarin.Forms' _namespace_所需的'using'語句? – Curiousity

回答

0

如果你真的都有點吃力,爲什麼你就不能這樣做:

public PhrasesFrame() 
    { 
     InitializeComponent(); 
     correctButton.Clicked += correctButtonClicked; 
     resetButton.Clicked += resetButtonClicked; 
     faveLabel.BackgroundColor = Color.Red; 
     faveLabel.GestureRecognizers.Add(new TapGestureRecognizer 
     { 
      Command = new Command(() => 
      { 
       AS.phrase.Favorite = !AS.phrase.Favorite; 
       if (AS.phrase.Favorite) 
       { 
         faveLabel.TextColor = Color.Red; 
       } 

       App.DB.UpdateFavorite(AS.phrase.Favorite, AS.phrase.PhraseId); 
      }) 
     }); 
    } 

在相同的點創建您的命令,你分配給它允許你在正確的指針關聯到標籤。另外,除非你關心在其他地方使用方法'FaveLabelTapped()',否則沒有重要的需要將其重構爲其自己的方法。

編輯:

有可能它沒有解決在運行時正確地引用了「顏色」類,所以你也可以嘗試:

void FaveLabelTapped() 
{ 
    AS.phrase.Favorite = !AS.phrase.Favorite; 
    if (AS.phrase.Favorite) { 
     // this gives an error 
     faveLabel.TextColor = Xamarin.Forms.Color.Red; //Change this to include the assembly reference. 
    } 
    App.DB.UpdateFavorite(AS.phrase.Favorite, AS.phrase.PhraseId); 
} 
+1

謝謝。我會試試看。但不知道爲什麼其他方式不行。在一個方法中這樣做的原因是不希望在具有這個部分類的不同文件之間分割功能。你有什麼想法,爲什麼把它移出來的方法會停止顏色分配工作? – Alan2

+0

可能存在運行時衝突,請問您的派生類中包含名爲'Color'的屬性的程序集是否存在? – Digitalsa1nt

相關問題