将eventhandler赋予生成按钮后面的自定义代码

时间:2012-03-20 07:27:16

标签: c# silverlight windows-phone-7

大家好我如何给我的按钮一个eventhanlder b2.Click + = new RoutedEventHandler(BtnChiefAns); 我试过了,它没有用

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

ButtonLeft b2 = new ButtonLeft();

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

这是我自定义按钮的代码

<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>

我需要能够点击此按钮:(提前致谢!

2 个答案:

答案 0 :(得分:0)

由于这是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.
}

答案 1 :(得分:0)

如果您的UserControl只有一个Button,则可以使用自定义样式创建Button而不使用UserControl。然后你可以用xaml或这样创建按钮:

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

这将更容易,更有效率

相关问题