简体   繁体   English

我的UserControl中的事件无法触发-为什么?

[英]Events in my UserControl won't fire up - why?

I placed a custom UserControl in my window and set the MouseDoubleClick event inside my usesr-control to change some of its properties. 我在窗口中放置了一个自定义UserControl,并在usesr-control内设置了MouseDoubleClick事件以更改其某些属性。

However, using breakpoints, I realized that the MouseDoubleClick event is never fired. 但是,使用断点,我意识到从不触发MouseDoubleClick事件。 That's true for any event I set in my user-control. 对于我在用户控件中设置的任何事件,都是如此。

What am I missing ? 我想念什么?

btw: I also created some DependencyProperty, "by the book", which works well, if it helps... 顺便说一句:我还创建了“依书”的DependencyProperty,如果有帮助,它会很好地工作...

Here is how to handle MouseDoubleClick in your UserControl . 这是在UserControl处理MouseDoubleClick的方法。

Create a new user control called UserControl1 . 创建一个名为UserControl1的新用户UserControl1 Here is the body of UserControl.xaml : 这是UserControl.xaml的主体:

<Grid Background="Red">
    <!-- leave this blank at first -->
</Grid>

We've set the background to red so we can see that we're working with the user control. 我们将背景设置为红色,以便可以看到我们正在使用用户控件。 Also, it needs a background in order to to receive the click events. 另外,它需要背景才能接收点击事件。

Add a double-click method override in the code-behind for the user control in UserControl1.xaml.cs : UserControl1.xaml.cs的用户控件的代码后面添加双击方法覆盖:

protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
    base.OnMouseDoubleClick(e);
    MessageBox.Show("Double-Click!");
}

Now create a window and add your user control to it, eg Window1.xaml : 现在创建一个窗口并向其中添加用户控件,例如Window1.xaml

<Grid>
    <local:UserControl1/>
</Grid>

Run your program so that Window1 is display and the whole window should be red. 运行您的程序,以便Window1 ,并且整个窗口应为红色。 Double-click on the window and you'll see a message-box: 双击窗口,您将看到一个消息框:

在此处输入图片说明

Once all this is working you can continue with whatever other goal you needed to use the double-click event for. 所有这些工作完成后,您可以继续使用双击事件所需的其他目标。

Set up background for you User Control . User Control设置背景。 It may be Transparent or White . 它可以是TransparentWhite

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

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