简体   繁体   中英

WPF how to capture mouse events on UserControl contentTemplates

I have this little UserControl, it's just a button. I want to do some cool things with it like capture a gesture and other things one would want from a custom control.

My problem is I cannot write the event handle for MouseEnter because I can't address the members of a ContentTemplate like a regular UserControl.

Normally I:

<Grid>
    <Label Name="hover" Content="hover me"/>
</Grid>

And I can address in C#

this.hover.MouseEnter += handler;

My goal is to apply that use-case to this other UserControl using a ContentTempalte

<UserControl x:Class="project.my_button" <!-- omitted for brevity --> >
<UserControl.ContentTemplate>
    <DataTemplate>
        <Border BorderBrush="#FFFFFFFF" BorderThickness="1" >
            <Grid Name="hover">
                <ContentPresenter Content="{TemplateBinding Content}"/>
            </Grid>
        </Border>
    </DataTemplate>
</UserControl.ContentTemplate>

Try this

<UserControl x:Class="Stackoverflow.ButtonUC"
         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" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Button>
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Height="100" Width="200" Background="Red" MouseEnter="Grid_MouseEnter_1" Margin="20">
                    <ContentPresenter Content="{TemplateBinding Property=Content}"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>

.cs

   public partial class ButtonUC : UserControl
{
    public ButtonUC()
    {
        InitializeComponent();
    }

    private void Grid_MouseEnter_1(object sender, MouseEventArgs e)
    {

    }

}

If you want to subscribe this event in Window where you will apply this control then you can create an event in this usercontrol and subscribe it in Window class and fire that event from the above handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM