Ala*_*an2 10 c# xaml xamarin xamarin.forms
我有这个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>
Run Code Online (Sandbox Code Playgroud)
在我的C#代码中,我很熟悉设置标签的Text属性,只需指定如下:
sampleLabel.Text = "ABC"
Run Code Online (Sandbox Code Playgroud)
但这种情况有所不同.有人可以告诉我如何在单击标签时从C#更改标签的颜色.
那这个呢:
主页:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
视图模型:
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));
}
}
Run Code Online (Sandbox Code Playgroud)