点击标签各自的父项(列表视图的项)后,如何更改标签的文本颜色



我有一个使用ItemTemplate的ListView。我想在点击项目时更改相应的标签文本颜色。

我的代码的相关部分:

public class Especialidade
{
public string id { get; set; }
public string especialidade { get; set; }
public Color color { get; set; }
}
public List<Especialidade> ListaEspecs;

我正在手动设置ListView ItemsSource,而不使用绑定:

ListViewEspecs.ItemsSource = ListaEspecs;

应该更改颜色的代码(颜色应该自动绑定(

async void ListViewEspecs_ItemTapped(System.Object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
var x = e.Item as Especialidade;
x.color = Color.Orange;
}

Xaml

<ListView x:Name="ListViewEspecs" ItemTapped="ListViewEspecs_ItemTapped" Grid.Column="0" Grid.Row="1" SelectionMode="None" BackgroundColor="Transparent" SeparatorVisibility="None" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" VerticalScrollBarVisibility="Never" SeparatorColor="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Margin="0,0,0,5"> 
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label Text="{Binding especialidade}" Grid.Column="1" Grid.Row="0" FontSize="16" HorizontalTextAlignment="Start" HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand" TextColor="{Binding color}" />
</Grid> 
</ViewCell> 
</DataTemplate> 
</ListView.ItemTemplate>
</ListView>

标签文本按预期绑定,但当我点击该项时,应用程序会冻结,无一例外。我该怎么做?

同意@Jason您需要在模型中实现接口INotifyPropertyChanged

public class Especialidade : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string id { get; set; }
public string especialidade { get; set; }
Color _color;
public Color color
{
get { return _color; }
set {
if(_color!=value)
{
_color = value;
NotifyPropertyChanged("color");
}
}
}
}

此外,由于您使用了MVVM,因此最好将所有逻辑处理都放在ViewModel中。