WPF How to get a UserControl to inherit a Button?

2019-04-19 12:24发布

I created a UserControl which consists of a couple ellipses and labels. I added it just fine to another form and things were looking pretty snazzy.

Then I went to start adding some event handlers and discovered that the control I made did not expose a Click event. Oops. Easy to fix, right? Just go back to the code-behind on the UserControl I made and let it inherit Button.

Unfortunately, doing this caused a "Partial declarations of MyControl must not specify different base classes" message. This came as a surprise since I haven't declared any other base classes. Searching for the Partial in question returned no results either.

Is there a way to defeat this issue? If not, what would be the easiest workaround here? My goal is simply to get a Click event on the UserControl.

1条回答
Emotional °昔
2楼-- · 2019-04-19 12:51

Yes, you've declared other base classes :) Just trust compiler :)

When you writing <UserControl ...></UserControl> in XAML, you are subclassing UserControl. If you want to subclass a Button, use <Button ...></Button> instead and ": Button" in code-behind file.

But I'm strongly encourage you to not subclass Button, its an overkill for you task. You can use MouseLeftButtonUp event instead of the Click event.

查看更多
登录 后发表回答