如果您需要使用 Style 来实现,可以使用 Dynamic Styles in Xamarin.Forms。
在 ContentPage.Resources 中创建样式:
<ContentPage.Resources>
<Style x:Key="labelGreenStyle" TargetType="Label">
<Setter Property="TextColor" Value="Green" />
</Style>
<Style x:Key="labelRedStyle" TargetType="Label">
<Setter Property="TextColor" Value="Red" />
</Style>
</ContentPage.Resources>
标签的代码如下:
<Label Text="{Binding eMail}" Style="{DynamicResource myLabelStyle}" HorizontalOptions="CenterAndExpand"></Label>
<Label Text="{Binding eMail}" Style="{DynamicResource myLabelStyle}" HorizontalOptions="CenterAndExpand"></Label>
然后可以通过Button点击事件修改TextColor如下:
private void RedButton_Clicked(object sender, EventArgs e)
{
Resources["myLabelStyle"] = Resources["labelRedStyle"];
}
private void GreenButton_Clicked(object sender, EventArgs e)
{
Resources["myLabelStyle"] = Resources["labelGreenStyle"];
}
效果:
另外,您还可以在Xaml中为TextColor属性绑定一个颜色值,然后修改模型的数据可以动态改变TextColor。
例如,Contacts.cs项如下:
public class Contacts: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Address { get; set; }
public string eMail { get; set; }
private Color myColor;
public Color MyColor
{
set
{
if (myColor != value)
{
myColor = value;
OnPropertyChanged("MyColor");
}
}
get
{
return myColor;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后我们可以创建ContactViewModel.cs:
public class ContactViewModel
{
public List<Contacts> MyList { set; get; }
public ContactViewModel()
{
MyList = new List<Contacts>();
MyList.Add(new Contacts() { Address = "1", eMail = "1111@11.com", MyColor = Color.Red });
MyList.Add(new Contacts() { Address = "2", eMail = "2222@22.com" });
MyList.Add(new Contacts() { Address = "3", eMail = "3333@33.com" });
MyList.Add(new Contacts() { Address = "4", eMail = "4444@44.com" });
MyList.Add(new Contacts() { Address = "5", eMail = "5555@55.com" });
}
}
XAML代码如下:
<ListView x:Name="MyListView"
ItemsSource="{Binding MyList}"
ItemSelected="MyListView_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal"
VerticalOptions="Center">
<Label Text="Hello World" TextColor="{Binding MyColor}"
HorizontalOptions="StartAndExpand"></Label>
<Label Text="{Binding Address}"
HorizontalOptions="CenterAndExpand"></Label>
<Label Text="{Binding eMail}"
HorizontalOptions="CenterAndExpand"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我会以选择项目后修改文字颜色为例。
public partial class PageListView : ContentPage
{
public PageListView()
{
InitializeComponent();
BindingContext = new ContactViewModel();
}
private void MyListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as Contacts;
item.MyColor = Color.Green;
}
}
效果: