How to wire up a click event for a custom usercontrol button? Should I use CustomControl?

假如想象 提交于 2019-12-04 02:43:24
Reed Copsey

The easiest option would be to just make your UserControl expose a click event, and pass through your Button's click event.

In MyButton's xaml:

<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">

In MyButton's code:

public event RoutedEventHandler Click;

void onButtonClick(object sender, RoutedEventArgs e)
{
    if (this.Click != null)
    {
        this.Click(this, e);
    }
}

You can then leave your "implementation" code as-is.

The answer really depends on what your goals are for the control. You may be able to get away with not creating a user or custom control if you can manipulate the data that you are binding to. If all you want to do is display a dynamic image and text, then you could create an ImageText object that contains two properties. You could then bind the default Button control's Content property to this object and use a DataTemplate to define the layout of the content.

If you cannot control the data type that you are binding to, or if you're really set on the idea of creating a control then I would recommend creating a custom control. Custom controls allow you to utilize the built-in capabilities of a standard button. Generally you would only want to create a User Control if you wanted to hide or encapsulate the default functionality of the visual controls contained within the control.

Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!