WPF CanFreeze Freeze IsFrozen

FredGrit發表於2024-08-25

Freezable—The base class for objects that can be “frozen” into a read-only state for performance reasons. Freezables, once frozen, can be safely shared among multiple threads, unlike all other DispatcherObjects. Frozen objects can never be unfrozen,but you can clone them to create unfrozen copies. Most Freezables are graphics primitives such as brushes, pens, and geometries or animation classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp281
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Grid grid { get; set; }
        SolidColorBrush bgBrush { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            GridBackgroundFreezeUnFreeze();
        }

        
        private void GridBackgroundFreezeUnFreeze()
        {
            grid = new Grid();
            grid.ToolTip = "Brush CanFreze Freeze IsFrozen Clone";
            bgBrush = new SolidColorBrush(Colors.Red);
            if(bgBrush.CanFreeze)
            {
                bgBrush.Freeze();
            }
            grid.Background= bgBrush;
            this.Content = grid;
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if(bgBrush.IsFrozen)
            {
                SolidColorBrush blueBrush = bgBrush.Clone();
                blueBrush.Color = Colors.Blue;
                grid.Background= blueBrush;

            }
            else
            {
                grid.Background = new SolidColorBrush(Colors.Blue);
            }
        }
    }
}

相關文章