Checkbox_Command_Binding - lucyberryhub/WPF.Tutorial GitHub Wiki
Welcome to the super sweet tutorial where weβll bind checkboxes in a WPF application, and weβre going to do it with a cherry-berry twist! ππ
In this section, we will create a super cute ViewModel that holds our berry sweet data and controls the checkbox action. ππΈ
Weβll use the CherryBerryCollection (like ObservableCollection
) to hold our Berry items, and weβll use BerrySweetCommand to handle the checkbox action when it's clicked. ππ
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace BerryBerryApp
{
public class BerryViewModel<BerryType> : BaseBerryViewModel where BerryType : class, new()
{
// The collection of berry types (like strawberries, cherries, etc.)
public ObservableCollection<BerryType> BerryBasket { get; set; }
// The sweet command that handles checkbox clicks
public ICommand BerryClickCommand { get; }
public BerryViewModel()
{
// Create a basket of berries with a default Berry type (like Strawberry!)
BerryBasket = new ObservableCollection<BerryType> { new BerryType() };
// Set the command for the checkbox
BerryClickCommand = new BerrySweetCommand<BerryType>(OnBerryChecked);
}
// The method that gets triggered when you click a berry checkbox
private void OnBerryChecked(BerryType berry)
{
if (berry != null)
{
// Update the berry basket (like saving berry preferences!)
SaveBerryState(BerryBasket);
}
}
// Sweet method to update the berry state and save it in a cute file
public void SaveBerryState<BerryType>(ObservableCollection<BerryType> berryBasket)
{
// Saving the basket of berries into the berry file
SaveBerryToFile(berryBasket);
}
// A super cute method to serialize and save the berry basket to a file
public void SaveBerryToFile<BerryType>(IEnumerable<BerryType> berries)
{
// Serialize and save the berry collection to a cute JSON file
string berryJson = Newtonsoft.Json.JsonConvert.SerializeObject(berries, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("berryBasket.json", berryJson);
Console.WriteLine($"Saved berry basket with {berries.Count()} sweet berries of type {typeof(BerryType).Name}");
}
}
}
-
BerryBasket
: The sweet collection of berries. This is like the basket where we keep our cute berry items! π -
BerryClickCommand
: This is the magic spell that runs when you click on the checkbox (the berry checkbox!). πβ¨ -
OnBerryChecked
: This method is triggered when you click the checkbox. It's like checking if the berry has been picked! πΈπ -
SaveBerryState
: After the berry gets picked, we save the basket (all the berry changes) to the file. ππ -
SaveBerryToFile
: The method that saves your berry basket to a cute JSON file. πβ¨
The BerrySweetCommand class is like the fairy that makes sure our checkbox does its magic when clicked! ππ§ββοΈβ¨
using System;
using System.Windows.Input;
namespace BerryBerryApp
{
public class BerrySweetCommand<BerryType> : ICommand
{
private readonly Action<BerryType> _execute;
private readonly Func<BerryType, bool> _canExecute;
public BerrySweetCommand(Action<BerryType> execute, Func<BerryType, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute((BerryType)parameter);
}
public void Execute(object parameter)
{
_execute((BerryType)parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
-
BerrySweetCommand
: This class is the berry magic wand! π It makes sure that the checkbox can perform an action when clicked. -
CanExecute
: This tells the command whether it can be executed or not. π It checks if the action can happen. For example, if the berry is ripe and ready to be picked! π -
Execute
: This is the magic trick! When the checkbox is clicked, it runs this method, and the berry gets saved! π
Here, weβll define our Berry Model (the berry item). It could be any kind of berry like Strawberry, Cherry, etc. π
public class Berry
{
public bool IsBerryPicked { get; set; }
}
-
IsBerryPicked
: This property represents if a berry has been picked (checked in the checkbox). ππ
Letβs bind the checkbox to the Berry Basket in our View (the XAML). πβ¨ We will use two-way binding so when the checkbox is clicked, the berry state gets updated! ππ
<Window x:Class="BerryBerryApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Berry Berry Checkbox Binding" Height="350" Width="525">
<Grid>
<CheckBox x:Name="chk_Berry"
IsChecked="{Binding BerryBasket[0].IsBerryPicked, Mode=TwoWay}"
Command="{Binding BerryClickCommand}"
CommandParameter="{Binding BerryBasket[0]}"
Content="Pick the Berry!" Margin="0,5" VerticalAlignment="Top"/>
</Grid>
</Window>
-
IsChecked
: Weβre binding it toIsBerryPicked
from the first berry in the basket (BerryBasket[0]). π -
Command
: We bind this to the BerryClickCommand that will be triggered when the checkbox is clicked. πβ¨ -
CommandParameter
: We pass the first berry in the basket to the command. Itβs like sending the berry as a gift! ππ
Hereβs the MainWindow.xaml.cs where we set up our BerryViewModel. π We tell it which Berry type we want to use, and weβll bind it to the UI.
public partial class MainWindow : Window
{
private BerryViewModel<Berry> berryViewModel;
public MainWindow()
{
InitializeComponent();
// Create a viewmodel with the Berry model (Strawberry or Cherry!)
berryViewModel = new BerryViewModel<Berry>();
DataContext = berryViewModel;
}
}
-
BerryViewModel<Berry>
: This creates the ViewModel with our Berry type, so it can hold the berry data! π -
DataContext
: This binds the ViewModel to the UI so the checkbox and other UI elements can access it. ππ
The final piece of our tutorial is the berry-saving method. Weβre going to serialize our Berry Basket and save it as a cute JSON file.
public void SaveBerryToFile<BerryType>(IEnumerable<BerryType> berries)
{
// Serialize and save the berry collection to a cute JSON file
string berryJson = Newtonsoft.Json.JsonConvert.SerializeObject(berries, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("berryBasket.json", berryJson);
Console.WriteLine($"Saved berry basket with {berries.Count()} sweet berries of type {typeof(BerryType).Name}");
}
-
SaveBerryToFile
: This method saves the basket of berries to a JSON file so we can keep track of the berry states! ππ -
File.WriteAllText
: This writes the serialized berry collection into a file. Itβs like preserving the berry collection! πβ¨
Now you have a super cute MVVM-based checkbox binding where we interact with our Berry Basket! π Weβve made it extra sweet and berry-themed for all you lovely coders! ππ
Hereβs a recap of the steps:
- Create a Berry ViewModel to hold the Berry Basket and handle checkboxm clicks.
- Use BerrySweetCommand to trigger
actions when the checkbox is clicked. 3. Bind the checkbox to your Berry Model in XAML using two-way binding. 4. Save the Berry Basket into a cute JSON file so you can track your berry picking progress! ππ
Thatβs all, sweeties! πΈπ Now you can create your own Berry Basket app in a super cute way! πβ¨
π Code your heart out, and may your berries always be sweet! π