In WPF, how can I handle an event in the ItemsControl ControlTemplate

I am trying to handle an event inside an ItemsControl ControlTemplate. I assigned the MouseUp and MouseDown events to the button (btnRight below). The problem is, when I click on the button, the event never reaches my code. How do events in ControlTemplates work and what do I need to do to do it? I've tried assigning events to an encoded button during the OnApplyTemplate event to no avail.

Thank you for your help!

<ItemsControl.Template>
    <ControlTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="36" />
                <ColumnDefinition />
                <ColumnDefinition Width="36" />
            </Grid.ColumnDefinitions>
            <Button x:Name="btnLeft" Grid.Column="0" Height="36">
                <Button.Template>
                    <ControlTemplate>
                        <Image>
                            <Image.Source>
                                <BitmapImage UriSource="Images\left.png" />
                            </Image.Source>
                        </Image>
                    </ControlTemplate>
                </Button.Template>
            </Button>
            <Border Grid.Column="1" BorderBrush="Black" BorderThickness="1" Background="Black" Padding="6">
                <ItemsPresenter Margin="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=MarginOffset}" />
            </Border>
            <Button x:Name="btnRight" Grid.Column="2" Height="36" MouseUp="btnRight_MouseUp" MouseDown="btnRight_MouseDown">
                <Button.Template>
                    <ControlTemplate>
                        <Image>
                            <Image.Source>
                                <BitmapImage UriSource="Images\right.png" />
                            </Image.Source>
                        </Image>
                    </ControlTemplate>
                </Button.Template>
            </Button>
        </Grid>
    </ControlTemplate>
</ItemsControl.Template>

      

+2


source to share


1 answer


Instead of using button click events, create a new command, bind the Command property to the Button to the command you created, and then add a CommandBinding to your custom control to handle the command as it runs.



See here for more information.

+1


source







All Articles