2

I want to copy the content of one text box to another text box by clicking the mouse.

How do I bind a mouse click event?

JimiLoe
  • 950
  • 2
  • 14
  • 22
user456871
  • 21
  • 1
  • 1
  • 2
  • 1
    Can you describe the scenario of the mouse click a bit more. Does the mouse have to be in a specific area or on a certain control, or just any mouse click? Also are you wanting to simulate a click or a double click? – Val Sep 24 '10 at 04:08
  • Maybe this answers your question: http://stackoverflow.com/questions/1035023/firing-a-double-click-event-from-a-wpf-listview-item-using-mvvm/1510592#1510592 – jbe Sep 28 '10 at 19:47

7 Answers7

9

This sample is for RightClick, but you can adjust the event according to your needs:

<TextBox>
    <TextBox.InputBindings>
        <MouseBinding Gesture="RightClick" Command="{Binding YourCommand}" />
    </TextBox.InputBindings>
</TextBox>

Edit: I uploaded on my SkyDrive a sample app that illustrates how to use this method in order to achieve exactly what you need. Please be advised that it will only work for .NET Framework 4+

Claudiu Constantin
  • 2,138
  • 27
  • 38
  • Will this work? I don't think you can use Binding like this... It will complain that "A 'Binding' cannot be set on the 'Command' property of type 'MouseBinding'. A 'Binding' can only be set on a DependencyProperty of a Dependency Object. What do you think? – Ann Sanderson Mar 21 '12 at 20:43
  • Unfortunately it won't work due to this: http://connectppe.microsoft.com/VisualStudio/feedback/details/687703/mousebinding-doesnt-work-in-listview-and-treeview – Matt H Jul 03 '12 at 00:49
  • 1
    OK, people, it will work only when targeting .NET 4. For previous versions it will throw the error specified by Ann Sanderson – Claudiu Constantin Jul 04 '12 at 05:34
3

Want to add a behavior to a control ? Just use the Ramora pattern !

Jonathan ANTOINE
  • 9,021
  • 1
  • 23
  • 33
  • While I admit Ramora pattern's utility, I think its complexity is not suitable for what user456871 needs; there are other more simple solutions – Claudiu Constantin Jul 04 '12 at 05:41
2

Hope this helps

Use this code for TreeView

<TreeView commandBehaviors:MouseDoubleClick.Command="{Binding YourCommand}"
          commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}"
          .../>

Use this code for TreeViewItem

<TreeView ItemsSource="{Binding Projects}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="commandBehaviors:MouseDoubleClick.Command"
                    Value="{Binding YourCommand}"/>
            <Setter Property="commandBehaviors:MouseDoubleClick.CommandParameter"
                    Value="{Binding}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

Use this code to create a new behavior MouseDoubleClick

public class MouseDoubleClick
{
    public static DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        typeof(ICommand),
        typeof(MouseDoubleClick),
        new UIPropertyMetadata(CommandChanged));

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter",
                                            typeof(object),
                                            typeof(MouseDoubleClick),
                                            new UIPropertyMetadata(null));

    public static void SetCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(CommandProperty, value);
    }

    public static void SetCommandParameter(DependencyObject target, object value)
    {
        target.SetValue(CommandParameterProperty, value);
    }
    public static object GetCommandParameter(DependencyObject target)
    {
        return target.GetValue(CommandParameterProperty);
    }

    private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Control control = target as Control;
        if (control != null)
        {
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                control.MouseDoubleClick += OnMouseDoubleClick;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                control.MouseDoubleClick -= OnMouseDoubleClick;
            }
        }
    }

    private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = (ICommand)control.GetValue(CommandProperty);
        object commandParameter = control.GetValue(CommandParameterProperty);
        command.Execute(commandParameter);
    }
}
Ashish Singh
  • 275
  • 3
  • 5
  • 1
    Great answer, thanks! Note: In the ItemContainerStyle, you'll probably have to use the Command binding `{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.YourCommand}`, assuming the top level control is a Window (switch to UserControl or whatever is appropriate otherwise) – Pakman Oct 05 '20 at 16:18
1

It sounds like you are inventing a new behaviour for your textbox :)

I would just consider if the users of your program understands and likes this behaviour.

Maybe it is easier to understand the funcionality if it is just a button you have to click - it is also faster to implement :)

Rune Andersen
  • 1,650
  • 12
  • 15
0

You can easily do this by creating a new behavior.

<TextBox 
    MouseDoubleClick="SelectAddress" 
    GotKeyboardFocus="SelectAddress" 
    PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />

Here's the code behind:

private void SelectAddress(object sender, RoutedEventArgs e)
{

    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        tb.SelectAll();
    }

}

private void SelectivelyIgnoreMouseButton(object sender, 
        MouseButtonEventArgs e)

{

    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
         if (!tb.IsKeyboardFocusWithin)
        {
            e.Handled = true;
            tb.Focus();
        }
    }
}

Please update this snippet according to your need.

Ashish Singh
  • 275
  • 3
  • 5
0

I think you could bind mouse gestures to commands. Take a look at this: http://www.thejoyofcode.com/Invoking_a_Command_on_a_Double_Click_or_other_Mouse_Gesture.aspx

AndrewS
  • 3,450
  • 1
  • 21
  • 26
0

I'm not sure what exactly you're wanting to bind to.

There is no readily available MouseClick event as far as i'm aware.

the Click event as you'd find on a Button is inherited from ButtonBase and is not readily available on most controls.

MouseDoubleClick is inherited from Control and available on anythning deriving from it.

in your example it sounds like a simple Button with its Click event handled might do the trick.

To bind to the click event, you just need to specify the event handler for the event in the Button.

Something like:

XAML:

<TextBox Name=TextBoxOne />
<TextBox Name=TextBoxTwo />

<Button Click="CopyTextButton_Click"/>

And in your code behind:

void CopyTextButton_Click(object sender, RoutedEventArgs e)
{
    //Copy the text and anything else you need done
}

Otherwise if this is a more specialised scenario, you might want to investigate using a UserControl or as AndrewS answered above, a Command.

Hope it helps.

Val
  • 930
  • 6
  • 10
  • ok thx. im thinking of putting a button 'behind' the textbox (custom textbox + button user control) to achieve this. So when the user clicks on the text, the button gets the event... thx guys for the help. i will try this out. – user456871 Sep 24 '10 at 05:21