wpf draw ellipse via mouse click

FredGrit發表於2024-03-28
<Window x:Class="WpfApp21.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:WpfApp21"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Canvas x:Name="cvs" Background="Cyan"   MouseDown="cvs_MouseDown" MouseUp="cvs_MouseUp"/>
    </Grid>
</Window>


//xaml.cs
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 WpfApp21
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Point pt;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cvs_MouseDown(object sender, MouseButtonEventArgs e)
        {
            pt = e.GetPosition(cvs);
            cvs.CaptureMouse();
            DrawEllipse();
        }

        private void DrawEllipse()
        {
            Ellipse elp = new Ellipse();
            elp.Width = 50;
            elp.Height=50;
            elp.Fill = new SolidColorBrush(Colors.Red);
            elp.Stroke = new SolidColorBrush(Colors.Blue);
            Canvas.SetLeft(elp,(int)pt.X);
            Canvas.SetTop(elp,(int)pt.Y);
            cvs.Children.Add(elp);  
        }

        private void cvs_MouseUp(object sender, MouseButtonEventArgs e)
        {
            cvs.ReleaseMouseCapture();
        }
    }
}

It's odd when i don't set the background of the canvas and click the mouse there is no response

While I set the background of the canvas the mouse click works immediately,I can't figure out the root cause,so amazing

//no explicitly background setting,click not work
<Canvas x:Name="cvs"    MouseDown="cvs_MouseDown" MouseUp="cvs_MouseUp"/>


//set the background of canvas via random value it works immediately

<Canvas x:Name="cvs" Background="Cyan"   MouseDown="cvs_MouseDown" MouseUp="cvs_MouseUp"/>

相關文章