TextBox添加鼠标按下、失去焦点、鼠标移动等事件及重写

28 篇文章 1 订阅
文章详细介绍了如何在WPF中为TextBox添加LostFocus、PreviewMouseDown事件,并使用命令模式进行处理。同时,展示了创建一个自定义TextBox控件,该控件包含了焦点变化、鼠标按下等行为的定制,如自动清除焦点、Backspace键删除选中内容等功能。
摘要由CSDN通过智能技术生成

TextBox添加鼠标按下、失去焦点、鼠标移动等事件及重写

方法1:

//xaml
<TextBox Grid.Column="2" Grid.Row="0" x:Name="TBSeriesDescription" Text="{Binding CurrentSeries.ReconSeriesDescription,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"  VerticalAlignment="Stretch" FontSize="14" MaxLength="50">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="LostFocus">
            <i:InvokeCommandAction Command="{Binding TBSeriesDescriptionLostFocusCommand}" CommandParameter="{Binding ElementName=TBSeriesDescription}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="PreviewMouseDown">
            <i:InvokeCommandAction Command="{Binding TBSeriesDescriptionPreviewMouseDownCommand}" CommandParameter="{Binding ElementName=TBSeriesDescription}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>


//文本框焦点失去事件
public ICommand TBSeriesDescriptionLostFocusCommand { get; private set; }
//鼠标按下事件
public ICommand TBSeriesDescriptionPreviewMouseDownCommand { get; private set; }

//初始化
TBSeriesDescriptionLostFocusCommand = new DelegateCommand<object>(TBSeriesDescriptionLostFocusCommand_Execute);
TBSeriesDescriptionPreviewMouseDownCommand = new DelegateCommand<object>(TBSeriesDescriptionPreviewMouseDownCommand_Execute);

//文本框焦点失去事件触发的方法
private void TBSeriesDescriptionLostFocusCommand_Execute(object control)
{
    TextBox textBox = control as TextBox;
    textBox.SelectionLength = 0;
}
//鼠标按下事件
private void TBSeriesDescriptionPreviewMouseDownCommand_Execute(object control)
{
    TextBox tb = control as TextBox;
    if (tb == null || tb.IsFocused)
    {
        return;
    }
    tb.Focus();
}

方法2:

//TextBox类
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Common.Control
{
    /// <summary>
    /// 定制的TextBox
    /// </summary>
    public class CustomizedTextBox : TextBox
    {
        public CustomizedTextBox()
        {
            this.GotFocus += CustomizedTextBox_GotFocus;
            this.LostFocus += CustomizedTextBox_LostFocus;
            this.PreviewMouseDown += this.CustomizedTextBox_PreviewMouseDown;
            //this.GotMouseCapture += this.CustomizedTextBox_GotMouseCapture;
            //this.MouseLeave += this.CustomizedTextBox_MouseLeave;
            this.PreviewKeyDown += CustomizedTextBox_PreviewKeyDown;
        }

        /// <summary>
        /// 按下Backspace键,直接替换选择的文本框内容部分为空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {            
            TextBox tb = sender as TextBox;
            if (tb == null)
            {
                return;
            }
            if (e.Key == Key.Back && tb.SelectionLength > 0)
            {
                int start = tb.SelectionStart;
                int length = tb.SelectionLength;
                tb.Text = tb.Text.Remove(start, length);
                tb.SelectionStart = start;
            }
        }

        /// <summary>
        /// 鼠标离开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_MouseLeave(object sender, MouseEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null)
            {
                return;
            }
            Keyboard.ClearFocus();
        }

        /// <summary>
        /// 获取鼠标捕获事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_GotMouseCapture(object sender, MouseEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null || tb.IsFocused)
            {
                return;
            }
            tb.Focus();
            //e.Handled = true;
        }

        /// <summary>
        /// 获得焦点时,文本框内容全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null)
            {
                return;
            }
            tb.SelectAll();
            设置光标闪烁的位置
            //tb.CaretIndex = tb.Text.Length;
        }

        /// <summary>
        /// 文本框焦点失去事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            textBox.SelectionLength = 0;
        }

        /// <summary>
        /// 鼠标按下时,如果未获得焦点,获得焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustomizedTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null || tb.IsFocused)
            {
                return;
            }
            tb.Focus();
            e.Handled = true;
        }

    }
}

//样式:
 <Style x:Key="CustomizedTextBoxStyle" TargetType="{x:Type TextBox}">
        <Setter Property="MaxLength" Value="50"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="BorderBrush" Value="{StaticResource SolidBrush_Gray10}" />
        <Setter Property="CaretBrush" Value="White"/>
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="MinHeight" Value="26" />
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border SnapsToDevicePixels="True" CornerRadius="2" Background="{TemplateBinding Control.Background}" BorderBrush="{TemplateBinding Control.BorderBrush}" BorderThickness="{TemplateBinding Control.BorderThickness}">
                        <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True">
                            <Setter Value="{StaticResource SolidBrush_Gray3}" Property="BorderBrush" />
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Value="{StaticResource SolidBrush_Gray3}" Property="BorderBrush" />
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Value="0.5" Property="Opacity" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

//页面
<commonControl:CustomizedTextBox Grid.Column="2" Grid.Row="0" Text="{Binding CurrentSeries.ReconSeriesDescription,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Style="{StaticResource CustomizedTextBoxStyle}"/>

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangnaisheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值