Изменить цвет метки Xamarin Forms на С# только, нет XAML
У меня есть этот код XAML:
<StackLayout Grid.Row="0" Grid.Column="0" Padding="15,10,20,10" HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="tapFavorites" NumberOfTapsRequired="1" />
</StackLayout.GestureRecognizers>
<Label x:Name="faveLabel" FontFamily="FontAwesome" XAlign="Center" FontSize="23">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="true">
<Setter Property="TextColor" Value="Red" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="false">
<Setter Property="TextColor" Value="Gray" />
</DataTrigger>
</Label.Triggers>
</Label>
</StackLayout>
В моем коде С# я знаком с установкой свойства Text метки, просто указав вот так:
sampleLabel.Text = "ABC"
Но эта ситуация другая. Может кто-то сказать мне, как я могу изменить цвет метки с С#, когда на нее нажимают.
Ответы
Ответ 1
Как насчет этого:
![введите описание изображения здесь]()
MainPage:
public partial class MainPage : ContentPage
{
MyViewModel vm;
public MainPage()
{
InitializeComponent();
vm = new MyViewModel();
BindingContext = vm;
var faveLabel = new Label { FontSize = 24, FontFamily = "FontAwesome", Text = "Tap Here !" };
var trigger1 = new DataTrigger(typeof(Label));
trigger1.Binding = new Binding("Favorite", BindingMode.TwoWay);
trigger1.Value = true;
trigger1.Setters.Add(new Setter { Property = Label.TextColorProperty, Value = Color.Red });
var trigger2 = new DataTrigger(typeof(Label));
trigger2.Binding = new Binding("Favorite", BindingMode.TwoWay);
trigger2.Value = false;
trigger2.Setters.Add(new Setter { Property = Label.TextColorProperty, Value = Color.Gray });
faveLabel.Triggers.Add(trigger1);
faveLabel.Triggers.Add(trigger2);
var sl = new StackLayout {
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand
};
var tgr = new TapGestureRecognizer();
tgr.NumberOfTapsRequired = 1;
tgr.Tapped += tapFavorites;
sl.GestureRecognizers.Add(tgr);
sl.Children.Add(faveLabel);
Content = sl;
}
public void tapFavorites(object sender, EventArgs e)
{
vm.Favorite = !vm.Favorite;
}
}
ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool favorite;
public bool Favorite
{
get { return favorite; }
set
{
if (value != favorite)
{
favorite = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Ответ 2
Вы можете получить доступ к своему файловому имени faveLabel и GestureRecognizer. Там вы установите TextColor вашего ярлыка на другой. Вместо ввода кода после функции стрелки вы также можете предоставить функцию.
faveLabel.GestureRecognizers.Add( new TapGestureRecognizer { Command = new Command( () => faveLabel.TextColor = Color.Red ) });
Вместо ввода полного кода после функции стрелки вы также можете предоставить функцию.
... { Command = new Command(() => OnLabelClicked() ) }
Здесь есть ссылка на официальную документацию Xamarin для (Tap) GestureRecognizers.
Ответ 3
Если вы делаете что-то в xaml, то триггеры - это путь, но если вы делаете это в коде, вы можете сделать это в любом случае - с помощью или без триггеров
Вы можете сохранить цвет избранного и/или ярлык текста в модели и сделать привязку или нет. Если у вас есть модель, вы также можете привязать tapFavorites, как показала Маримба.
public partial class MainPage : ContentPage
{
Label faveLabel;
bool favorite = false;
public MainPage()
{
InitializeComponent();
faveLabel = new Label { FontSize = 24, FontFamily = "FontAwesome", Text = "Tap Here !" };
var sl = new StackLayout {
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand
};
var tgr = new TapGestureRecognizer();
tgr.NumberOfTapsRequired = 1;
tgr.Tapped += tapFavorites;
sl.GestureRecognizers.Add(tgr);
sl.Children.Add(faveLabel);
Content = sl;
}
public void tapFavorites(object sender, EventArgs e)
{
favorite = ! favorite;
faveLabel.TextColor = favorite ? Color.Red : Color.Gray;
}
}