I have a predefined list of items in CollectionView and each item includes a checkbox. The checkbox is binded to a Preference. What I want to do is automatically update the checkbox in CollectionView when the preference is updated. How can I do this?
public class AchievementsViewModule : BaseViewModel
{
public ObservableCollection<Achievement> Achievements { get; set; }
public AchievementsViewModule()
{
Achievements = new ObservableCollection<Achievement>();
Achievements.Add(new Achievement
{
Title = "first title",
Subtitle = "first subtitle",
ImageUrl = "image.png",
Completed = Preferences.get("item1",False),
CompletedDate = DateTime.Now
});
Achievements.Add(new Achievement
{
Title = "second title",
Subtitle = "second subtitle",
ImageUrl = "image.png",
Completed = Preferences.get("item2",False),
CompletedDate = DateTime.Now
});
Achievements.Add(new Achievement
{
Title = "third title",
Subtitle = "third subtitle",
ImageUrl = "image.png",
Completed = Preferences.get("item3",False),
CompletedDate = DateTime.Now
});
}
In a separate page, a button changes the Preference value:
private void Button_Clicked(object sender, EventArgs e)
{
Preferences.Set("item2", True);
}
And here's the Achievement module
public class Achievement
{
public string Title { get; set; }
public string Subtitle { get; set; }
public DateTime CompletedDate { get; set; }
public Boolean Completed { get; set; }
public string ImageUrl { get; set; }
}
The XAML for Achievements page:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.Views.AchievementsPage"
xmlns:viewmodels="clr-namespace:App1.ViewModels"
xmlns:model="clr-namespace:App1.Models"
x:DataType="model:Achievement">
<ContentPage.BindingContext>
<viewmodels:AchievementsViewModule></viewmodels:AchievementsViewModule>
</ContentPage.BindingContext>
<StackLayout>
<CollectionView x:DataType="viewmodels:AchievementsViewModule"
SelectionMode="Single"
ItemsSource= "{Binding Achievements}"
SelectionChanged="CollectionView_SelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10"
x:DataType="model:Achievement"
RowDefinitions="Auto, *"
ColumnDefinitions="Auto, *">
<Image Grid.RowSpan="2" BackgroundColor="Red"
Source="{Binding ImageUrl}"
Aspect="AspectFill"
HeightRequest="50"
WidthRequest="50" />
<Label Grid.Column="1" HorizontalOptions="StartAndExpand" BackgroundColor="Green"
Text="{Binding Title}"
FontAttributes="Bold" />
<Label Grid.Row="1" HorizontalOptions="Start" BackgroundColor="Yellow"
Grid.Column="1"
Text="{Binding Subtitle}"
VerticalOptions="End" />
<CheckBox Grid.RowSpan="2"
"Grid.Column="3"
IsChecked="{Binding Completed}" </CheckBox>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage>