繁体   English   中英

将事件处理程序提供给生成的按钮后面的自定义代码

[英]Giving eventhandler to a customized code behind generated button

大家好,我该如何为我的按钮设置事件处理程序b2。单击+ = new RoutedEventHandler(BtnChiefAns); 我尝试过了,但是没有用

我的按钮是自定义按钮这是调用它的代码

ButtonLeft b2 =新的ButtonLeft();

当我这样做b2.Click + = new RoutedEventHandler(BtnChiefAns); 它将突出显示Click单词,并说出““自定义用户控件””中未知的成员“ Click”

这是我自定义按钮的代码

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:edc="clr-namespace:Microsoft.Expression.Controls;assembly=Microsoft.Expression.Drawing"
mc:Ignorable="d"
x:Class="Volunteer.LayoutRootControl" Height="127" Width="200">
<UserControl.Resources>
    <Style x:Key="ButtonStyle8" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <edc:Callout AnchorPoint="0.85,1.19" CalloutStyle="Rectangle" Fill="#FFE054EF" FontSize="14.666999816894531" Stroke="Black"/>
                        <ContentPresenter Height="96" Width="196"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

<Button Style="{StaticResource ButtonStyle8}" HorizontalAlignment="Left" Height="102" VerticalAlignment="Top" Width="200">
    <Button.Content>
        <StackPanel Orientation="Horizontal" Width="197" Margin="-40,-34,-41,-32">
            <TextBlock Width="196" x:Name="BtnIN3" Text="" FontSize="22" TextWrapping="Wrap" Margin="0,0,0,-12" Height="95" />
        </StackPanel>
    </Button.Content>
</Button>

我需要能够单击此按钮:(预先感谢!

由于这是一个UserControl,所以它没有Click事件。 您需要实现它。

在UserControl的代码中,添加以下内容:

public event RoutedEventHandler Click;

然后,钩住XAML中的Button的click事件,并在实现中,编写如下内容:

if (Click != null)
{
  Click(this, e); // Where "e" is the parameter you got from the button.
}

如果您的UserControl仅具有一个Button ,则可以创建没有UserControl具有自定义样式的Button 然后,您可以用xaml或这种方式创建按钮:

Button b = new Button()
{
     Style = (Style)Application.Current.Resources["ButtonStyle8"]
};
b.Click += ...

这将更容易,更有效

暂无
暂无

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

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