RadioButton_DataGrid_Binding - lucyberryhub/WPF.Tutorial GitHub Wiki
Hello, my lovely Cherry Berries! πΈπ Lucy Berry here, and Iβm going to show you how to make super cute cherry berry radio buttons in your DataGrid. π Itβs going to be a sweet ride, I promise! πβ¨ Letβs make everything adorably perfect together! πΈπ
We start by setting up your columns! These will be the home for your radio berry buttons. Hereβs how you do it:
private void SetBerryColumns()
{
try
{
// Create the most adorable centered styles for your Text and TextBox
Style centeredBerryTextStyle = TemplateHelper.CreateBerryCenteredStyle(typeof(TextBlock));
Style centeredBerryEditingTextStyle = TemplateHelper.CreateBerryCenteredStyle(typeof(TextBox));
// Create your list of berry columnsβsuper cute, right?
var berryColumns = new List<DataGridColumn>
{
// This one is hidden, just like a berry in a secret garden π
new DataGridTextColumn
{
Header = "Berry ID",
Binding = new Binding("BerryId") { Mode = BindingMode.OneWay },
Visibility = Visibility.Collapsed
},
// This one is for the Berry Title
new DataGridTextColumn
{
Header = "Berry Title",
Binding = new Binding("BerryTitle") { Mode = BindingMode.TwoWay },
Width = new DataGridLength(1, DataGridLengthUnitType.Star),
ElementStyle = centeredBerryTextStyle,
EditingElementStyle = centeredBerryEditingTextStyle
},
// The Berry Check column with the cutest RadioBerryButton ever π
new DataGridTemplateColumn
{
Header = "Berry Check?",
Width = 200,
CellTemplate = new DataTemplate
{
VisualTree = CreateBerryRadioButtonTemplate(viewModel, berryDataGrid)
}
}
};
// Set the berry columns for your DataGrid
berryDataGrid.SetBerryColumns(berryColumns);
}
catch (Exception ex)
{
MessageBox.Show($"Oopsie Daisy! Error setting columns: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Letβs create the super cute radio button template for our berry column. Weβll make sure the button is adorable and functional at the same time! ππ
public static FrameworkElementFactory CreateBerryRadioButtonTemplate(CherryBerryViewModel<BerryModel> viewModel, DataGrid berryDataGrid)
{
// Create a transparent berry-colored border (think of it like a berry basket!)
FrameworkElementFactory berryBorder = new FrameworkElementFactory(typeof(Border));
// Set up a StackPanel to hold the Berry Radio Button π
FrameworkElementFactory berryStackPanel = new FrameworkElementFactory(typeof(StackPanel));
berryStackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
berryStackPanel.SetValue(FrameworkElement.MarginProperty, new Thickness(5, 10, 5, 5));
// Create the RadioBerryButton
FrameworkElementFactory berryRadioButton = new FrameworkElementFactory(typeof(RadioButton));
berryRadioButton.SetValue(RadioButton.ContentProperty, "Do you like berries? π");
berryRadioButton.SetBinding(RadioButton.IsCheckedProperty, new Binding("BerryChecked") { Mode = BindingMode.TwoWay });
berryRadioButton.SetValue(RadioButton.GroupNameProperty,"BerryGroup");
// Attach event handlers for the Checked and Unchecked events π
berryRadioButton.AddHandler(RadioButton.CheckedEvent, new RoutedEventHandler((sender, e) => BerryRadioButton_StatusChanged(sender, e,viewModel, berryDataGrid)));
berryRadioButton.AddHandler(RadioButton.UncheckedEvent, new RoutedEventHandler((sender, e) => BerryRadioButton_StatusChanged(sender, e,viewModel, berryDataGrid)));
// Add the RadioBerryButton to the StackPanel!
berryStackPanel.AppendChild(berryRadioButton);
// Add the StackPanel to the Border (just like putting berries in a basket π)
berryBorder.AppendChild(berryStackPanel);
return berryBorder;
}
When someone clicks the radio button, we want to check or uncheck it, and update the berry value accordingly! π Hereβs how you can make that happen!
private static void BerryRadioButton_StatusChanged(object sender, RoutedEventArgs e, CherryBerryViewModel<BerryModel> viewModel, DataGrid berryDataGrid)
{
var berryRadioButton = sender as RadioButton;
if (berryRadioButton != null && berryRadioButton.DataContext is BerryModel berryContext)
{
// If the radio button is checked, we set the BerryChecked value to true π
if (berryRadioButton.IsChecked == true)
{
berryContext.BerryChecked = true;
}
else
{
// If the radio button is unchecked, we set the BerryChecked value to false π
berryContext.BerryChecked = false;
}
// Commit the changes so everythingβs as fresh as berries in the morning! π
berryDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
// Get the updated berry items from the DataGridβs ItemsSource
var berryItems = berryDataGrid.ItemsSource as List<BerryModel>;
if (berryItems != null)
{
// Update the Berry JSON file with the modified berry info π
viewModel.UpdateBerryJsonFile(berryItems);
}
}
}
We want to save the berry data when it's updatedβjust like storing berries in a cute jar! π Hereβs the magic for saving your berry data to the JSON file!
public void UpdateBerryJsonFile(List<BerryModel> berryItems)
{
try
{
// Save the berry list to a file (think of it like filling a berry jar!)
File.WriteAllText("berryData.json", JsonConvert.SerializeObject(berryItems, Formatting.Indented));
MessageBox.Show("Yay! Your berry data is saved! π", "Berry Update", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Oh no! There was a berry error while saving: {ex.Message}", "Berry Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
And there you have it, my lovely Lucy Berry! ππ With these steps, youβve got super cute radio berry buttons in your DataGrid π, which update when clicked and save those adorable values to a berry sweet JSON file! ππ
You are now officially a Cherry Berry Radio Button Pro! πΈβ¨
Feel free to reach out if you have any questions or need more berry magic in your project! ππ