简体   繁体   English

WPF如何捕获UserControl contentTemplates上的鼠标事件

[英]WPF how to capture mouse events on UserControl contentTemplates

I have this little UserControl, it's just a button. 我有这个小的UserControl,它只是一个按钮。 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. 我的问题是我无法为MouseEnter编写事件句柄,因为我无法像常规UserControl那样访问ContentTemplate的成员。

Normally I: 通常我:

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

And I can address in C# 我可以用C#寻址

this.hover.MouseEnter += handler;

My goal is to apply that use-case to this other UserControl using a ContentTempalte 我的目标是使用ContentTempalte将用例应用于其他UserControl

<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 .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. 如果要在Window中订阅此事件,将在其中应用此控件,则可以在此用户控件中创建一个事件,并在Window类中对其进行订阅,然后从上述处理程序中触发该事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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