首页 > 解决方案 > Click element within Data Grid Column Header

问题描述

I have applied a custom style to my DataGrid's column headers. Here is a simplified version of it:

<Style x:Key="DataGridColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DataGridColumnHeader">
                <Grid>
                    <Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
                        <Grid>
                            <StackPanel Orientation="Horizontal">
                                <ContentPresenter Margin="5 0 5 0" HorizontalAlignment="Center" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                                <Image IsHitTestVisible="True" Source="pin.png">
                                    <Image.InputBindings>
                                        <MouseBinding MouseAction="LeftClick" Command="{x:Static myView:MyCommand}" CommandParameter="{Binding}" />
                                    </Image.InputBindings>
                                </Image>
                            </StackPanel>
                        </Grid>
                    </Border>
                    <Thumb x:Name="PART_LeftHeaderGripper" Style="{StaticResource DataGridColumnHeaderResizeThumb}"/>
                    <Thumb x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right" Style="{StaticResource DataGridColumnHeaderResizeThumb}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I am struggling to get the command to fire when clicking the image. Is there something I am missing? Is there a different way that I can fire a command when clicking an element (i.e. an image) within the DataGridColumnHeader?

Some more details: MyCommand is defined in the Window's CommandBindings. I have not included this code here. I have other commands defined similarly for other elements (i.e. DataGridCell) that work OK. It seems there is something specific to the way the DataGridColumnHeader element that prevents the command to be fired.

标签: c#wpfxamlwpfdatagrid

解决方案


似乎您正在绑定到MyCommandxmlns 下的类型myView;相反,您应该绑定到MyCommand(假设类MyCommand实现ICommand)的实例。你可以考虑在这里实现单例。或者您可以定义MyCommand任何地方的静态实例。


推荐阅读