Hello,
You can do this with data binding and ValueConverter
. Please refer to the steps and documentation below.
Step 1. Add a bool attribute to the model class to mark whether this Item is selected or not.
public class Item : INotifyPropertyChanged
{
public string Id { get; set; }
public string Text { get; set; }
public string Description { get; set; }
private bool isSelected { get; set; }
public bool IsSelected
{
get => isSelected;
set
{
isSelected = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Step 2. Implement ValueConverter to return different colors by whether the item is selected or not.
public class BoolToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value == true)
{
return Color.Red;
}
else
{
return Color.Green;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Color.Red : Color.Green;
}
}
Step 3. Setting the binding for a Label in ListView
<Label Text="{Binding Description}"
LineBreakMode="NoWrap"
BackgroundColor="{Binding IsSelected,Converter={StaticResource BoolToBrush}}"
FontSize="13" />
Step 4. Since the notification feature was previously implemented in the Item, you can have the ValueConverter automatically change the color when selected and unselected by simply changing the value of IsSelected
.
private void ItemsListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as Item;
if (item != null)
{
item.IsSelected = true;
}
}
Xamarin support ended on May 1, 2024 for all Xamarin SDKs including Xamarin.Forms. For more information, please check: Xamarin official support policy | .NET (microsoft.com). We will recommend you upgrade Xamarin projects to . NET MAUI, please see the Upgrade from Xamarin to .NET & .NET MAUI documentation.
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.