WPF Canvas ItemsControl, MouseLeftButtonDown reload data, right save as jpg file and display via Proceess

 private void SaveAsJPGCommandExecuted(object? obj)
 {
     var fe = obj as FrameworkElement;
     if (fe!=null)
     {
         SaveFrameworkElementAsJpg(fe);
     }
 }

 private void SaveFrameworkElementAsJpg(FrameworkElement fe)
 {
     if (fe==null)
     {
         return;
     }

     RenderTargetBitmap rtb = new RenderTargetBitmap((int)maxWidth*dpiFactor, 
         (int)maxHeight*dpiFactor,
         96*dpiFactor, 96*dpiFactor,
         PixelFormats.Pbgra32);

     DrawingVisual drawingVisual = new DrawingVisual();
     using (DrawingContext drawingContext = drawingVisual.RenderOpen())
     {
         VisualBrush visualBrush = new VisualBrush(fe);
         drawingContext.DrawRectangle(visualBrush, null, new Rect(0, 0, maxWidth, maxHeight));
     }

     rtb.Render(drawingVisual);

     string jpgFile = $"Canvas_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.jpg";
     JpegBitmapEncoder encoder = new JpegBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(rtb));

     using (FileStream fileStream = new FileStream(jpgFile, FileMode.Create))
     {
         encoder.Save(fileStream);
     }

     MessageBox.Show($"Saved in {jpgFile}");
     OpenJpgFile(jpgFile);
 }

         
 private void OpenJpgFile(string jpgFile)
 {
     var proc = new Process()
     {
         StartInfo=new ProcessStartInfo()
         {
             FileName=jpgFile,
             UseShellExecute=true,
         }
     };
     proc.Start();
 }

 

 

 

image

 

 

 

 

image

 

 

 

 

//xaml
<Window x:Class="WpfApp47.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp47"
        WindowState="Maximized"
        Background="White"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <behavior:Interaction.Triggers>
        <behavior:EventTrigger EventName="MouseLeftButtonDown">
            <behavior:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/>
        </behavior:EventTrigger>
    </behavior:Interaction.Triggers>
    <Window.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Save As JPG"
                      Command="{Binding SaveAsJPGCommand}"
                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},
                      Path=PlacementTarget}"/>
        </ContextMenu>
    </Window.ContextMenu>
    <Canvas Background="White">
        <ItemsControl ItemsSource="{Binding ElpsCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Canvas.Left" Value="{Binding X}"/>
                    <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                </Style> 
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Ellipse
                        Width="{Binding Width}"
                        Height="{Binding Height}"
                        Fill="{Binding FillBrush}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Canvas>
</Window>



//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
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 WpfApp47
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM(this);
            this.DataContext=vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        double maxWidth, maxHeight;
        private Window win;
        private int dpiFactor = 2;
        public MainVM(Window winValue)
        {
            win=winValue;
            if (win!=null)
            {
                win.Loaded+=Win_Loaded;
            }
        }

        private void Win_Loaded(object sender, RoutedEventArgs e)
        {
            maxWidth=win.ActualWidth;
            maxHeight=win.ActualHeight;
            InitElpsCollection();
        }

        private void InitElpsCollection()
        {
            Random rnd = new Random();
            ElpsCollection=new ObservableCollection<Elp>();
            for (int i = 0; i<100; i++)
            {
                ElpsCollection.Add(new Elp()
                {
                    Width=100,
                    Height=100,
                    X=rnd.Next(0, (int)maxWidth-100),
                    Y=rnd.Next(0, (int)maxHeight-100),
                    FillBrush=new SolidColorBrush(Color.FromRgb((byte)rnd.Next(0, 255), (byte)rnd.Next(0, 255),
                    (byte)rnd.Next(0, 255)))
                });
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var handler = PropertyChanged;
            if (handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        private ObservableCollection<Elp> elpsCollection;
        public ObservableCollection<Elp> ElpsCollection
        {
            get
            {
                return elpsCollection??new ObservableCollection<Elp>();
            }
            set
            {
                if (value!=null)
                {
                    elpsCollection=value;
                    OnPropertyChanged();
                }
            }
        }

        private ICommand mouseLeftButtonDownCommand;
        public ICommand MouseLeftButtonDownCommand
        {
            get
            {
                if (mouseLeftButtonDownCommand==null)
                {
                    mouseLeftButtonDownCommand=new DelCommand(MouseLeftButtonDownCommandExecuted);
                }
                return mouseLeftButtonDownCommand;
            }
        }

        private void MouseLeftButtonDownCommandExecuted(object? obj)
        {
            InitElpsCollection();
        }

        private ICommand saveAsJPGCommand;
        public ICommand SaveAsJPGCommand
        {
            get
            {
                if (saveAsJPGCommand==null)
                {
                    saveAsJPGCommand=new DelCommand(SaveAsJPGCommandExecuted);
                }
                return saveAsJPGCommand;
            }
        }

        private void SaveAsJPGCommandExecuted(object? obj)
        {
            var fe = obj as FrameworkElement;
            if (fe!=null)
            {
                SaveFrameworkElementAsJpg(fe);
            }
        }

        private void SaveFrameworkElementAsJpg(FrameworkElement fe)
        {
            if (fe==null)
            {
                return;
            }

            RenderTargetBitmap rtb = new RenderTargetBitmap((int)maxWidth*dpiFactor, 
                (int)maxHeight*dpiFactor,
                96*dpiFactor, 96*dpiFactor,
                PixelFormats.Pbgra32);

            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                VisualBrush visualBrush = new VisualBrush(fe);
                drawingContext.DrawRectangle(visualBrush, null, new Rect(0, 0, maxWidth, maxHeight));
            }

            rtb.Render(drawingVisual);

            string jpgFile = $"Canvas_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.jpg";
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));

            using (FileStream fileStream = new FileStream(jpgFile, FileMode.Create))
            {
                encoder.Save(fileStream);
            }

            MessageBox.Show($"Saved in {jpgFile}");
            OpenJpgFile(jpgFile);
        }

                
        private void OpenJpgFile(string jpgFile)
        {
            var proc = new Process()
            {
                StartInfo=new ProcessStartInfo()
                {
                    FileName=jpgFile,
                    UseShellExecute=true,
                }
            };
            proc.Start();
        }
    }

    public class Elp
    {
        public double Width { get; set; }
        public double Height { get; set; }
        public double X { get; set; }
        public double Y { get; set; }
        public SolidColorBrush FillBrush { get; set; }
    }

    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute= executeValue;
            canExecute= canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested+=value;
            }
            remove
            {
                CommandManager.RequerySuggested -=value;
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute==null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }
    }
}

 

posted @ 2025-08-19 22:56  FredGrit  阅读(6)  评论(0)    收藏  举报