I am trying to control the background color of a label by changing the color of the selected label. I am following the MVVM pattern, and the way I have implemented is like:
In the Model I have created a boolean, with get and set, which has to detect if an item in my listview is selected.
public boolean Selected {get; set;}
In my view, I bind the background color property to the boolean, and set the IValueConverter as the Converter
- In the ViewModel, I implement the get and set
It seems that it only checks once, as the background color is always white. I have checked it with breakpoints in the Converter, and it only gets called when the list is initiated, but not when the items are updated.
IValueConverter:
public class SelectedItemColorConverter : IValueConverter
{
#region IValueConverter implementation
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
if ((Boolean)value)
return Color.Red;
else
return Color.White;
}
return Color.White;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
This is the ListView:
<StackLayout x:Name="standingsStackLayout" IsVisible="False">
<ListView x:Name="standingsList" SeparatorColor="Black" ItemsSource="{Binding StandingsListSource}" SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label x:Name="TournamentNameLabel" Text="{Binding TournamentName}"
TextColor="{StaticResource textColor}" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
BackgroundColor="{Binding Selected, Converter={StaticResource colorConvert}}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
ViewModel code:
public HistoricalStandingsData _selectedItem;
public HistoricalStandingsData SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
if(_selectedItem != null)
_selectedItem.Selected = false;
_selectedItem = value;
if (_selectedItem != null)
_selectedItem.Selected = true;
TournamentLabelName = _selectedItem.TournamentName;
OnPropertyChanged(nameof(SelectedItem));
//OnPropertyChanged(nameof(_selectedItem.Selected));
}
}
}
I have added the <ContentPage.Resources>
for the Converter