Why can't I tap/click blank areas inside of a

2019-01-28 07:28发布

问题:

I finally was able to create an "easy" transparent button control, based off a ContentControl. However, can someone explain why I couldn't click/tap any blank areas of the control until I set the background of the child element to transparent? I ran into this issue also when:

  • I tried to use Border
  • I set the ControlTemplate of a button rather than the ContentTemplate.

Here's my "button" class:

public class TransparentButton : ContentControl {
    public TransparentButton() {            
        HorizontalContentAlignment = HorizontalAlignment.Stretch;
    }

    public override void OnApplyTemplate() {
        var child = Content as Grid;

        if (child != null) {
            child.Background = new SolidColorBrush(Colors.Transparent);
        }

        base.OnApplyTemplate();
    }
}

It's pretty specific to my cases when using (assuming a Grid child) but it works. The reason I use it is for lists (non-ListBox) with the TiltEffect enabled.

Context of the issue:

<ItemsControl x:Name="Items" toolkit:TiltEffect.IsTiltEnabled="True">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <controls:TransparentButton 
                cal:Message.Attach="[Event Tap] = [Action Go($dataContext)]">
                <Grid>
                    <StackPanel HorizontalAlignment="Left">
                        <TextBlock Text="{Binding Test}" />                            
                    </StackPanel>
                    <StackPanel HorizontalAlignment="Right">
                        <TextBlock Text="{Binding Test2}" />                            
                    </StackPanel>
                </Grid>
            </controls:TransparentButton>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

If you click between the StackPanels inside the item, no event gets fired and nothing happens. Only when the Grid's Background is Transparent does it "take up space".

I come from a web background so this is confusing; a containing element should be "hit testable" even when it's background isn't set.

回答1:

An object with no background is usually called as hollow or non-hittable in XAML terms. So it is must to set a background to make the object respond to hits. To achieve hit test for an transparent object, you should set the background to transparent.

More information about hit testing

http://msdn.microsoft.com/en-us/library/ms752097.aspx