WPF 自定义控件实现定时自动读秒

目标:使用自定义控件实现双击控件自动读秒并且跳出弹窗,控件自动读秒倒计时,弹窗显示当前时间。

1.添加一个自定义控件,在控件里面添加一个Border控件,设置相关属性,再在border中添加一个TextBlock控件,读秒时间显示在TextBlock中。

控件设计Generic.Xaml代码如下:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyControl1">

    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <Border Background="Purple"
                            BorderBrush="Black"
                            BorderThickness= "2"
                            Width="200" Height="150">
                        <TextBlock x:Name="MyTbl" Margin="50,50" Background="LightYellow"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

2.在后台代码中需要添加两个依赖属性,这里用一个string类型的Times属性用来设置读秒的时间,一个ICommand类型的Clickcmd接口用来binding ViewModel里面的command的函数。

后台逻辑CustumControl1.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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 MyControl1
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:MyControl1"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:MyControl1;assembly=MyControl1"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用,
    /// 并重新生成以避免编译错误:
    ///
    ///     在解决方案资源管理器中右击目标项目,然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:CustomControl1/>
    ///
    /// </summary>
    public class CustomControl1 : Control
    {
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
        }

        //添加一个string类型的 属性 Times
        public string Times
        {
            get { return (string)GetValue(TimesProperty); }
            set { SetValue(TimesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Times.  This enables animation, styling, binding, etc...
        //注册依赖属性,PropertyMetadata是给属性元数据,也就是属性的默认值
        public static readonly DependencyProperty TimesProperty =
            DependencyProperty.Register("Times", typeof(string), typeof(CustomControl1), new PropertyMetadata("6"));


        //添加命令属性
        public ICommand Clickcmd
        {
            get { return (ICommand)GetValue(ClickcmdProperty); }
            set { SetValue(ClickcmdProperty, value); }
        }

        //注册依赖属性,PropertyMetadata是给属性元数据,也就是属性的默认值
        // Using a DependencyProperty as the backing store for Clickcmd.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ClickcmdProperty =
            DependencyProperty.Register("Clickcmd", typeof(ICommand), typeof(CustomControl1), new PropertyMetadata(null));


        //重写OnApplyTemplate方法,用户在使用该控件时系统会自动调用的方法。
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            //给事件添加方法
            MouseDoubleClick += CustomControl1_MouseDoubleClick;
        }

        //需要添加的方法
        private void CustomControl1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //1.读秒功能的实现
            //请求需要的元素TextBlock
            var tem = GetTemplateChild("MyTbl") as TextBlock;
            string s = tem.Text;
            //将属性Times的值赋给Text
            tem.Text = Times;
            var temint = int.Parse(Times);
            Task.Run(() =>
            {
                do
                { 
                    //跨线程访问数据
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        tem.Text = (temint--).ToString();
                        Times = temint.ToString();
                    });
                    Thread.Sleep(1000);
                }
                while (temint != 0);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    tem.Text = s;
                });
            });

            //2.弹出对话框的实现
            //通过ICommand接口绑定ViewModel里Command函数
            Clickcmd.Execute(this);
        }
    }
}

3.ViewModel代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Prism;
using Prism.Commands;
using Prism.Mvvm;

namespace MyControl1
{
    internal class ViewModel:BindableBase
    {
        public ViewModel()
        {
            ClickCmd = new DelegateCommand(Click);
        }

        public DelegateCommand ClickCmd { get; set; }

        public void Click() 
        {
            MessageBox.Show(DateTime.Now.ToString());
        }
    }

}

4.在MainWindow中使用自定义控件:

<Window x:Class="MyControl1.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:MyControl1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:CustomControl1 Times="6" Clickcmd="{Binding ClickCmd}"/>
    </Grid>
</Window>

注意:在MainWindow.Xmal.cs中记得设置数据源!!!

namespace MyControl1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //数据源!!!
            this.DataContext = new ViewModel();
        }
    }
}

5.实现效果如下:

 双击后:

MainWindow 2023-08-24 10-04-45

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在WPF中,我们可以通过自定义件来实现消息提示功能。 首先,我们可以创建一个继承自ContentControl的自定义件,例如命名为MessageTipControl。在这个件中,我们可以定义一个Label或TextBlock用于显示提示信息。同时,可以为该件添加一些样式和动画以提升用户体验。 接下来,我们可以为MessageTipControl增加一些附加属性,例如MessageText和MessageType。这些属性可以用来设置提示信息的文本内容和类型,帮助我们在使用自定义件时更加便捷地进行设置。 然后,我们可以为自定义件添加一些额外的功能,例如自动隐藏、设置展示时长等等。我们可以使用定时器或动画来件的显示和隐藏,并可以根据需要定义一些事件或回调函数供外部调用。 最后,在需要显示消息提示的地方,我们可以引用自定义的MessageTipControl,并通过设置附加属性来显示特定的提示信息。例如可以通过在XAML中添加如下代码来完成: ``` <local:MessageTipControl MessageText="提示信息" MessageType="Success"/> ``` 当然,我们也可以通过动态绑定或代码的方式来实现消息提示的文本内容和类型的动态更新。 通过以上的步骤,我们就可以非常方便地使用自定义实现消息提示功能了。当需要显示提示时,我们只需调用相应的方法或设置相应的属性,件就能自动显示出消息提示,并根据设定的时间自动隐藏。这样可以使得我们的应用界面更加美观和用户友好。 ### 回答2: 使用WPF定义件可以很方便地实现消息提示功能。首先需要创建一个继承自WPF件的类,例如命名为MessageBox。在该类中,可以定义需要展示的消息内容、样式、位置等属性。通过重写OnRender方法,可以在件上绘制提示消息的样式。 在OnRender方法中,可以使用WPF的绘图API绘制背景、边框、文本等。可以通过依赖属性设置消息的文本内容、背景色、字体样式等。除此之外,可以使用WPF提供的动画效果来实现消息提示的弹出、消失的效果。 在使用该自定义件时,只需要在XAML文件中引用命名空间,并实例化MessageBox件即可。可以通过绑定消息内容属性来动态更改展示的消息内容。 此外,还可以定义一些方法,例如Show方法,用于制消息提示的显示与隐藏。可以设置动画效果实现消息提示的平滑弹出和淡出。 总结起来,使用WPF定义件可以很方便地实现消息提示功能。可以通过自定义件的属性和方法来制消息内容、样式和展示方式。这样可以在WPF应用程序中灵活地使用消息提示,提升用户体验。 ### 回答3: 使用WPF定义件可以很方便地实现消息提示功能。以下是实现步骤: 1. 创建自定义件类:创建一个继承自WPF件基类的自定义件类,可以命名为"MessageTip"。在该类中定义件的外观样式和交互行为。 2. 定义依赖属性:为了能够在使用该件时设置消息内容,需要在"MessageTip"类中定义一个依赖属性,例如"Message"。依赖属性可以支持数据绑定和样式设置。 3. 件模板:在自定义件的类中,可以使用"ControlTemplate"属性定义件的外观模板。可以使用XAML语言编写模板,在模板中指定消息内容的显示位置和样式。 4. 触发器和动画:可以使用触发器和动画效果来制消息提示的显示和隐藏。例如,可以在用户鼠标悬停在件上时显示消息,然后使用动画效果进行展开或淡入的动画效果,最后可以设置一定的时间后自动隐藏消息。 5. 使用自定义件:在WPF应用程序中,可以像使用其他件一样使用自定义件。在XAML中使用件名字,并设置相关属性,例如设置"Message"属性来显示具体的消息内容。 通过以上步骤,就可以使用WPF定义件来实现消息提示功能。自定义件具有良好的可复用性,可以在多个应用程序中进行使用,并且可以根据需要进行扩展和定制。此外,通过WPF的数据绑定功能,还可以通过绑定不同的数据源来显示不同的消息内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值