简体   繁体   中英

Simple WPF event question with custom control

Im making a custom button called "ShardButton" which uses a Style to control its content as well as its event triggers:

<Style x:Key="ButtonStyle" TargetType="{x:Type obj:ShardButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type obj:ShardButton}">
                <Grid>
                    <Path .../>
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                                      SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                      RecognizesAccessKey="True"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <EventTrigger RoutedEvent="ButtonBase.Click">
                        !!!SOMETHING HERE!!!
                    </EventTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Im using the above XAML in the main Window1.xaml file, and creating a xmlns to the "obj" namespace, so what I want to do is to call a custom event handling method on the ShardButton class, how do I do that in XAML?

I cant seem to find the right way to phrase it for a Google search...

Thanks for any help you can give me!

Mark

You can't directly execute event handlers in EventTriggers, they were'nt created for this purpose.

However, if every instance of your ShardButton must do the same thing on click, simply override the OnClick method in your ShardButton class and do whatever you have to do here.

If you don't desire this behavior but instead want to have a specific handler executed for each ShardButton instance that is using this specific style defined in Window1.xaml, add another setter:

<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type obj:Window1}}, Path=MyCommand}" />

Where MyCommand is an instance property of Window1 returning a custom implementation of ICommand that will invoke your handler. This line of code assumes that every button using this Style is somewhere in the visual tree of Window1, which should be probably the case (or the Style would be defined elsewhere).

You can use an EventSetter in your Style :

<Style ...>
    <EventSetter Event="Click" Handler="yourHandlerMethod"/>
</Style>

Then in your code-behind:

private void yourHandlerMethod(object sender, RoutedEventArgs e)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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