2017-07-17 105 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

相关问题