首页 > 其他分享 >WPF中控件拖放(二)——拖放示例

WPF中控件拖放(二)——拖放示例

时间:2024-09-25 11:02:39浏览次数:1  
标签:控件 circleUI string 示例 dataString Brush 拖放 converter

1.创建拖放对象

  1.1创建一个圆自定义控件,UI代码如下(Circle.xaml):  

<UserControl x:Class="WpfApp1.Circle"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             AllowDrop="True">
    <Grid>
        <Ellipse x:Name="circleUI" 
         Height="100" Width="100"
         Fill="Blue" />
    </Grid>
</UserControl>

  1.2Circle.xaml.cs文件输入以下代码

    1.2.0  自定义变量声明

        /// <summary>
        /// 用于存放原有brush值,便于撤销操作
        /// </summary>
        private Brush _previousFill = null;

 

    1.2.1  添加带参数构造函数      

        public Circle(Circle c)
        {
            InitializeComponent();
            this.circleUI.Height = c.circleUI.Height;
            this.circleUI.Width = c.circleUI.Height;
            this.circleUI.Fill = c.circleUI.Fill;
        }

    1.2.2  onm ouseMove事件重写,主要是用于将圆对象数据打包到DataObject对象

        /// <summary>
        /// 1.将圆形数据打包到 DataObject
        /// 2.调用静态 DragDrop.DoDragDrop 方法启动拖放操作
        /// </summary>
        /// <param name="e"></param>
        protected override void onm ouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                // Package the data.
                DataObject data = new DataObject();
                data.SetData(DataFormats.StringFormat, circleUI.Fill.ToString());
                data.SetData("Double", circleUI.Height);
                data.SetData("Object", this);

                // Initiate the drag-and-drop operation.
                DragDrop.DoDragDrop(this, data, DragDropEffects.Copy | DragDropEffects.Move);
            }
        }

    1.2.3  自定义拖拽过程中鼠标显示样式

        /// <summary>
        /// 设置自定义光标
        /// </summary>
        /// <param name="e"></param>
        protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
        {
            base.OnGiveFeedback(e);
            // These Effects values are set in the drop target's
            // DragOver event handler.
            if (e.Effects.HasFlag(DragDropEffects.Copy))
            {
                Mouse.SetCursor(Cursors.Cross);
            }
            else if (e.Effects.HasFlag(DragDropEffects.Move))
            {
                Mouse.SetCursor(Cursors.Pen);
            }
            else
            {
                Mouse.SetCursor(Cursors.No);
            }
            e.Handled = true;
        }

    1.2.4  处理已放置数据

        /// <summary>
        /// 处理已放置数据
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDrop(DragEventArgs e)
        {
            base.OnDrop(e);

            // 使用 GetDataPresent 方法检查拖动的数据是否包含字符串对象
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                //使用 GetData 方法提取字符串数据
                string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                //使用 BrushConverter 尝试将字符串转换为 Brush
                BrushConverter converter = new BrushConverter();
                if (converter.IsValid(dataString))
                {
                    Brush newFill = (Brush)converter.ConvertFromString(dataString);
                    //将画笔应用于提供圆形控件的 UI 的 Ellipse 的 Fill
                    circleUI.Fill = newFill;

                    // 判断是否按下ctrl键
                    if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey))
                    {
                 

    1.2.5 验证是否允许数据放置

        /// <summary>
        /// 验证是否允许数据放置
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDragOver(DragEventArgs e)
        {
            base.OnDragOver(e);
            e.Effects = DragDropEffects.None;

            // 使用 GetDataPresent 方法检查拖动的数据是否包含字符串对象
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                //使用 GetData 方法提取字符串数据
                string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                //使用 BrushConverter 尝试将字符串转换为 Brush
                BrushConverter converter = new BrushConverter();
                if (converter.IsValid(dataString))
                {
                    Brush newFill = (Brush)converter.ConvertFromString(dataString);
                    //将画笔应用于提供圆形控件的 UI 的 Ellipse 的 Fill
                    circleUI.Fill = newFill;

                    // 判断是否按下ctrl键
                    if (e.KeyStates.HasFlag(DragDropKeyS

    1.2.6  拖放过程中,鼠标进入后显示

        /// <summary>
        /// 拖放鼠标进入后显示
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);
            // 用于撤销操作
            _previousFill = circleUI.Fill;

            // If the DataObject contains string data, extract it.
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                // If the string can be converted into a Brush, convert it.
                BrushConverter converter = new BrushConverter();
                if (converter.IsValid(dataString))
                {
                    Brush newFill = (Brush)converter.ConvertFromString(dataString.ToString());
                    circleUI.Fill = newFill;
                }
            }
        }

    1.2.7拖放过程中,鼠标离开后显示

        /// <summary>
        /// 拖放鼠标进入后显示
        /// </summary>
        /// <param name="e"></param>
        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);
            // 用于撤销操作
            _previousFill = circleUI.Fill;

            // If the DataObject contains string data, extract it.
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                // If the string can be converted into a Brush, convert it.
                BrushConverter converter = new BrushConverter();
                if (converter.IsValid(dataString))
                {
                    Brush newFill = (Brush)converter.ConvertFromString(dataString.ToString());
                    circleUI.Fill = newFill;
                }
            }
        }

 

2.拖放具体操作实现

2.1  拖放操作实现UI,主要设置AllowDrop="True"以及设置设置相应的拖放事件

        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="0"
            Background="Beige"
            AllowDrop="True"
            DragOver="panel_DragOver"
            Drop="panel_Drop">
            <TextBox Width="Auto" Margin="2"
             Text="green"/>
            <local:Circle Margin="2" />
            <local:Circle Margin="2" />
        </StackPanel>
        <StackPanel Grid.Column="1"
            Background="Bisque"
            AllowDrop="True"
            DragOver="panel_DragOver"
            Drop="panel_Drop">
        </StackPanel>

2.2  拖放事件具体实现

  2.2.1  拖放过程中鼠标显示形式事件实现

        /// <summary>
        /// 拖放过程中鼠标的显示形式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("Object"))
            {
                // These Effects values are used in the drag source's
                // GiveFeedback event handler to determine which cursor to display.
                if (e.KeyStates == DragDropKeyStates.ControlKey)
                {
                    e.Effects = DragDropEffects.Copy;
                }
                else
                {
                    e.Effects = DragDropEffects.Move;
                }
            }
        }

  2.2.2 拖放操作具体实现

        /// <summary>
        /// 拖放操作具体实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel_Drop(object sender, DragEventArgs e)
        {
            //如果面板中的某个元素已经处理了放置,则面板不应同时处理该放置
            if (e.Handled == false)
            {
                Panel _panel = (Panel)sender;
                UIElement _element = (UIElement)e.Data.GetData("Object");

                if (_panel != null && _element != null)
                {
                    // 获取元素当前所属的面板,然后将其从该面板中删除,并将其添加到放置它的面板的 Children 中
                    Panel _parent = (Panel)VisualTreeHelper.GetParent(_element);

                    if (_parent != null)
                    {
                        if (e.KeyStates == DragDropKeyStates.ControlKey &&
                            e.AllowedEffects.HasFlag(DragDropEffects.Copy))
                        {
                            Circle _circle = new Circle((Circle)_element);

 

标签:控件,circleUI,string,示例,dataString,Brush,拖放,converter
From: https://www.cnblogs.com/echo-efun/p/18430902

相关文章

  • Element UI控件el-scrollbar定位布局
    ElementUI控件el-scrollbar定位布局基本概念与作用常见应用场景示例一:基本用法示例二:自定义滚动条样式示例三:嵌套滚动条示例四:监听滚动事件示例五:滚动到特定位置实际开发中的使用技巧ElementUI是一款基于Vue2.x的桌面端组件库,它提供了丰富的组件来帮助开发者......
  • 基于SSM的心理健康测试系统+微信小程序+LW参考示例
    系列文章目录1.基于SSM的洗衣房管理系统+原生微信小程序+LW参考示例2.基于SpringBoot的宠物摄影网站管理系统+LW参考示例3.基于SpringBoot+Vue的企业人事管理系统+LW参考示例4.基于SSM的高校实验室管理系统+LW参考示例5.基于SpringBoot的二手数码回收系统+原生微信小......
  • 在Activity中测量控件宽高的三种方式
    在进行Android开发时,有时需要测量控件的宽和高,常用的方式有以下三种:(1)重写onWindowFocusChanged(hasFocus:Boolean)方法,在这个方法内获取控件的宽高这个方法在Activity的窗口焦点发生变化时调用,具体可以分为窗口获得焦点时和窗口失去焦点时。Activity的焦点发生变化时,相关的......
  • C#在Winform中截图指定控件中的内容生成图像
    开发上位机过程中,收到需求:在软件跑完数据之后保存报告和图表截图。因为界面控件都做了大小拉伸缩放的适配,所以简单的设置截图起始点和长宽时无法满足需求的。所以要做一个根据控件本身大小来做截取动作的功能,所以我写了一个截取指定控件内图像的函数。 函数如下,只需传入控件,和存......
  • 车辆合格证识别接口-汽车管理智能化-python示例
    随着汽车行业的蓬勃发展和数字化进程的加快,如何高效、准确地管理车辆信息成为众多企业面临的重要挑战。新车合格证作为新车上牌、车辆注册和管理的重要凭证,其识别与录入的准确性直接关系到业务流程的顺畅。新车合格证识别接口应运而生,为汽车行业的各类企业提供了一种高效、智......
  • UIOTOS示例:自定义弹窗输出表单数据 | 前端低代码 前端零代码 web组态 无代码 amis gov
    目标对话框作为容器组件,可以隐藏掉默认的窗体头和脚,完全由内嵌页自定义,参见对话框自定义外观。并且也能获取弹窗纯表单数据,如下所示: 步骤内嵌页1.新建略。2.拖放组件拖放三个输入框,标识分别施志伟id、name、phone;两个按钮标识分别设置为cancel和ok 主页面1.新......
  • Spring事务传播机制(最全示例)
    我们在使用Spring框架进行开发时,经常在service层写很多方法,而且这些方法都是带事务的,那么Spring的事务怎么在多个方法之间传播呢?今天我们就仔细聊一聊。Spring的事务传播机制主要解决在多个方法之间,事务如何传递的问题,通常有7种传播类型:REQUIREDSUPPORTSMANDATORYREQUIRES_N......
  • MFC 之 Progress Control 控件的使用
    提到ProgressControl控件,大家可能会觉得在UI界面里面装一个进度条控件,一下就会让UI界面变得高级了些,所以可能会认为这个控件可能比较难搞。其实恰恰相反,这个控件使用起来特别容易,调用方法也就寥寥几个。不过本文重点内容并不是讲ProgressControl的使用,而是会重点介绍一......
  • DragDrop.DoDragDrop(DependencyObject, Object, DragDropEffects) 方法——控件拖动
    参数dragSourceDependencyObject对依赖项对象的引用(该对象是被拖动数据的源)。dataObject包含被拖动数据的数据对象。allowedEffectsDragDropEffectsDragDropEffects 值中的一个,指定拖放操作的允许效果。返回DragDropEffectsDragDropEffects 值中的一个,指定在拖......
  • 示例说明:sql语法学习
    SQL(StructuredQueryLanguage,结构化查询语言)是一种用于管理关系型数据库的标准语言。学习SQL可以帮助你有效地查询、插入、更新和删除数据库中的数据。以下是SQL语法的一些基本概念和常用命令:1.SQL基础语法SQL关键字:SQL语句通常以关键字开始,如SELECT、INSERT、UPDATE、DEL......