在WPF中,如何处理ItemsControl ControlTemplate中的事件

时间:2009-09-10 22:30:14

标签: wpf event-handling controltemplate

我正在尝试处理ItemsControl ControlTemplate中的事件。我已经分配了一个按钮的MouseUp和MouseDown事件(下面是btnRight)。问题是当我点击按钮时,事件永远不会到达我的代码隐藏。 ControlTemplates中的事件如何工作以及我需要做些什么来解决这个问题?我尝试在OnApplyTemplate事件期间将事件分配给代码隐藏中的按钮无效。

感谢您的帮助!

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

1 个答案:

答案 0 :(得分:1)

不是使用按钮单击事件,而是创建一个新命令,将Button的Command属性绑定到您创建的Command,然后将CommandBinding添加到用户控件以在执行时处理该命令。

请参阅here for了解更多信息。

相关问题