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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…