RadioButton_DataGrid_Binding - lucyberryhub/WPF.Tutorial GitHub Wiki

πŸ’ Cherry Berry Radio Button Tutorial πŸ“πŸ’–

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! πŸŒΈπŸ’


πŸ“ Step 1: Create Your Berry Columns πŸ’

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);
    }
}

πŸ’ Step 2: Create the Berry Radio Button Template πŸ“

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;
}

πŸ“ Step 3: Change the Radio Berry Button Status πŸ’

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);
        }
    }
}

πŸ’ Step 4: Update the Berry JSON File πŸ“

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);
    }
}

πŸ“ Conclusion πŸ’

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! πŸ’πŸ’–


⚠️ **GitHub.com Fallback** ⚠️