Capture mouse clicks on WPF TextBox

前端 未结 3 966
星月不相逢
星月不相逢 2021-02-03 21:25

I want to capture mouse clicks on a TextBox:



        
相关标签:
3条回答
  • 2021-02-03 21:33

    TextBox Class

    TextBox has built-in handling for the bubbling MouseUp and MouseDown events. Consequently, custom event handlers that listen for MouseUp or MouseDown events from a TextBox will not be called. If you need to respond to these events, listen for the tunneling PreviewMouseUp and PreviewMouseDown events instead, or register the handlers with the HandledEventsToo argument (this latter option is only available through code). Do not mark the event handled unless you deliberately want to disable TextBox native handling of these events, and be aware that this has notable effects on the control's UI.

    In you code you are firing just MouseLeftButtonUp

    0 讨论(0)
  • 2021-02-03 21:51

    Here's code example for those who are using MVVM

    It works fine for events that are inheriting from Control.

    In ViewModel:

    private ICommand _merchantRefereneceCommand;
    
    public ICommand MerchantReferenceCopyToClipboard
        {
            get { return _merchantRefereneceCommand ?? (_merchantRefereneceCommand = new MerchantRefereneceCommand(this)); }
            set { _merchantRefereneceCommand = value; }
        }
    
    public class MerchantRefereneceCommand : ICommand
        {
            private readonly PaymentViewModel _paymentViewModel;
    
            public MerchantRefereneceCommand(PaymentViewModel paymentViewModel)
            {
                _paymentViewModel = paymentViewModel;
            }
    
            public bool CanExecute(object parameter)
            {
                return true;
            }
    
            public void Execute(object parameter)
            {
                //Your code goes here.
            }
    
            public event EventHandler CanExecuteChanged;
        }
    

    In View (xaml):

    <TextBox Grid.Row="1" x:Name="MerchantReference" MaxLength="10" IsReadOnly="True"
                                 Text="{Binding MerchantReference, Mode=OneWay}"  >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDoubleClick" >
                <i:InvokeCommandAction Command="{Binding MerchantReferenceCopyToClipboard}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
    

    Hope this saves you some time.

    0 讨论(0)
  • 2021-02-03 21:53

    You can use the PreviewMouseDown event, and capture any clicks that way before the internal parts of the control process the click:

    <TextBox x:Name="t" PreviewMouseDown="TextBox_MouseDown" Height="32" Width="274" />
    
    0 讨论(0)
提交回复
热议问题