朧の.Netの足跡
問合せ先:support@oborodukiyo.info サイト内検索はこちら 
WPF 動的に長方形を追加する





動的に長方形を作成にするには、これが最適ではないかもしれませんが、こういうやり方もあるんだなと思っていただければと思います。
using System;
using System.Collections.Generic;
using System.Linq;
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 WPF_RectangleWithEvent
{
    public partial class Window1 : Window
    {
        //現在の長方形の開始座標と終了座標
        private Point _StartXY;
        private Point _EndXY;
        //動的に追加された長方形のコレクション
        private List<rectangle> _item = new List<rectangle>();
        public Window1()
        {
            InitializeComponent();
        }
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _StartXY = e.GetPosition(this.LayoutRoot);
            Rectangle rect = new Rectangle();
            this._item.Add(rect);
            
            rect.Fill = Brushes.Green;
            
            this.MouseMove += new MouseEventHandler(Rectangle_MouseMove);
            this.CaptureMouse();
            
            this.LayoutRoot.Children.Add(rect);
            rect.Width = 0;
            rect.Height = 0;
            
            e.Handled = true;
        }
        void Rectangle_MouseMove(object sender, MouseEventArgs e)
        {
            Rectangle rect = _item[_item.Count - 1];
            _EndXY = e.GetPosition(this.LayoutRoot);
            rect.Margin = new Thickness(_StartXY.X, _StartXY.Y, _EndXY.X, _EndXY.Y);
            rect.Width = _EndXY.X - _StartXY.X;
            rect.Height = _EndXY.Y - _StartXY.Y;
            rect.Stroke = Brushes.Blue;
            rect.StrokeThickness = 2;
        }
        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _EndXY = e.GetPosition(this.LayoutRoot);
            
            Rectangle rect = this._item[this._item.Count - 1];
            this.ReleaseMouseCapture();
            this.MouseMove -= Rectangle_MouseMove;
            rect.Focusable = true;
            rect.Margin = new Thickness(_StartXY.X, _StartXY.Y, _EndXY.X, _EndXY.Y);
            rect.Stroke = Brushes.Red;
            rect.StrokeThickness = 4;
            rect.Width = _EndXY.X - _StartXY.X;
            rect.Height = _EndXY.Y - _StartXY.Y;
            e.Handled = true;
        }
    }
}
    








良いやや良い普通やや悪い悪い

投稿日時評価コメント