如何为自定义用户控件按钮连接click事件?我应该使用CustomControl吗? [英] How to wire up a click event for a custom usercontrol button? Should I use CustomControl?

查看:226
本文介绍了如何为自定义用户控件按钮连接click事件?我应该使用CustomControl吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个以图像和文本块为内容的按钮.因此,我去寻找答案并找到了一个帖子( 可重复使用的按钮自定义内容 )告诉我创建一个用户控件.

I wanted to create a button that had an image and a textblock as content. So I went about looking for an answer and found a post (Reusable Custom Content for Buttons) which told me to create a usercontrol.

我做到了,效果很好.我可以通过依赖属性设置图像源和文本.但是,由于没有控件的点击事件,我被卡住了.

I did this and it works great. I can set the image source and text through dependency properties. However, I am stuck as there is no click event for my control.

我做了一些进一步的挖掘,得出的结论是,我可能需要一个从Button派生的CustomControl.这样对吗?还是将click事件连接到我的UserControl更好?

I did a little more digging and concluded that I probably need a CustomControl derived from Button. Is this correct? Or would it be better to wire up a click event to my UserControl?

这是我的UserControl:

Here's my UserControl:

<UserControl x:Class="Client.Usercontrols.MyButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">

    <Button Width="Auto" HorizontalAlignment="Center">
        <Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
            <Grid>
                <Image Name="tehImage" Source="{Binding ImageSource}" />
                <TextBlock Name="tehText" Text="{Binding Text}"
                           Style="{DynamicResource ButtonText}" />
            </Grid>
        </Border>
    </Button>
</UserControl>

实施

<my:MyButton ImageSource="../Images/MainSyncButton.png" ImageWidth="141" Text="Synchronise" Click="btnSynchronise_Click" />

推荐答案

最简单的选择是使UserControl公开click事件,并传递Button的click事件.

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

在MyButton的xaml中:

In MyButton's xaml:

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

使用MyButton的代码:

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.

这篇关于如何为自定义用户控件按钮连接click事件?我应该使用CustomControl吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆