WPF 鼠标绘制矩形

效果

WPF 鼠标绘制矩形_第1张图片

xaml部分

简单的用一个border和一个canvas就行【不一定要嵌套在border内部】

<Window x:Class="WPFtest.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:local="clr-namespace:WPFtest"
        mc:Ignorable="d"
        Title="MainWindow"
        Width="800"
        Height="500"
        WindowStyle="SingleBorderWindow">
    <Grid x:Name="grid" Width="400" Height="400">


        <Border Background="Transparent" BorderBrush="Black" BorderThickness="5" Width="400" Height="400" VerticalAlignment="Top" HorizontalAlignment="Left"
                MouseLeftButtonDown="Canvas_MouseButtonDown" 
                MouseLeftButtonUp="Canvas_MouseButtonUp" MouseMove="Canvas_MouseMove">
            <Canvas x:Name="canvas1" Background="Gray" Focusable="False"/>
        Border>
        
        <TextBlock x:Name="tb" VerticalAlignment="Top" HorizontalAlignment="Center">TextBlock>
    Grid>
Window>

C#文件

可以静态的在xaml文件中用rectangle,也可以在C#文件中创建Rectangle rec=new Rectangle();

public partial class MainWindow : Window
    {

        Rectangle rec=new Rectangle();
        public MainWindow()
        {
            InitializeComponent();
            
            rec.Stroke = Brushes.Red;
            rec.StrokeThickness = 0;
            canvas1.Children.Add(rec);
        }

        bool isMouseDowm = false;
        public Point startPoint;

        private void Canvas_MouseButtonDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(canvas1);
            isMouseDowm = true;
            rec.StrokeThickness = 2;
            tb.Text = "down  "+startPoint.X+" "+startPoint.Y;
        }

        private void Canvas_MouseButtonUp(object sender, MouseButtonEventArgs e)
        {
            isMouseDowm = false;
            tb.Text = "up";
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDowm)
            {
                var rect = new Rect(startPoint, e.GetPosition(canvas1));
                tb.Text = rect.Left + " " + rect.Top;
                rec.Margin = new Thickness(rect.Left, rect.Top, 0, 0);
                rec.Width = rect.Width;
                rec.Height = rect.Height;
            }
        }
    }

补充

如果想绘制多个矩形、或者其他图形可以借鉴wpf 鼠标拖动绘制几何图形【文章中矩形的长和高定义反了】

你可能感兴趣的:(C#,WPF,wpf)