简体   繁体   中英

How can I change the text color of a label after its respective parent(item of a listview) is tapped?

I have a ListView which uses an ItemTemplate. I want to change the respective label textcolor when the item is tapped.

The relevant parts of my code:

public class Especialidade
{
            public string id { get; set; }
            public string especialidade { get; set; }
            public Color color { get; set; }
}

public List<Especialidade> ListaEspecs;

I'm setting the ListView ItemsSource manually and not using binding:

ListViewEspecs.ItemsSource = ListaEspecs;

Code that is supposed to change the color(color should binds automatically)

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>

Label text is binding as expected but when I tap the item, the application freezes with no exception. How can I do that?

Agree with @Jason You need to implement the interface INotifyPropertyChanged in the model .

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");
            }

        }
    }

}

In Addition , since you had used MVVM , you would better put all the logic handling in ViewModel .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM