Search code examples
c#xamlimagebuttontextblock

TextBlock on top of ImageButton (Windows 8 XAML/C#)


Can someone give me an example of how to style a button with XAML hat has three states (hover, normal, pressed). i want the whole area of the button to be covered with an image (one for each of the three different states) and i want text to be on top that also has three different colors for the different states. i have something like this already (without the color states on the textblock). the problem i'm having at this point is that the textblock is blocking the input events for the button undernearth (i also haven't implemented the color changes for the textblock....

current code:

<DataTemplate x:Name="SubjectItemTemplate">
    <Canvas Width="225" Height="225">
        <Button Canvas.Left="0" Canvas.Top="0"
                Command="{Binding ElementName=LayoutRoot, Path=DataContext.NavigateToUnitsPage}"
                CommandParameter="{Binding}">
            <Button.Template>
                <ControlTemplate>
                    <Grid Background="{Binding LightThemeColor}" Width="205" Height="205">

                        <controls:ImageButton HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,0,0,0"
                                              NormalStateImageSource="{Binding ImageUriNormal}"
                                              HoverStateImageSource="{Binding ImageUriHover}"
                                              PressedStateImageSource="{Binding ImageUriPressed}" Command="{Binding ElementName=LayoutRoot, Path=DataContext.NavigateToUnitsPage}"
                CommandParameter="{Binding}"/>
                        <TextBlock Text="{Binding Name}" FontSize="18" TextWrapping="Wrap" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,168,0,0" />

                    </Grid>
                </ControlTemplate>
            </Button.Template>

        </Button>
    </Canvas>
</DataTemplate>

Solution

  • The reason that the ImageButton events are not being handled as expected with the TextBlock is because the TextBlock is located in-line with the ImageButton and not contained inside the ImageButton. To change this, the TextBlock has to be placed inside the ImageButton.

     <controls:ImageButton HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,0,0,0"
          NormalStateImageSource="{Binding ImageUriNormal}"
          HoverStateImageSource="{Binding ImageUriHover}"
          PressedStateImageSource="{Binding ImageUriPressed}" Command="{Binding ElementName=LayoutRoot, Path=DataContext.NavigateToUnitsPage}" CommandParameter="{Binding}" >
          <TextBlock Text="{Binding Name}" FontSize="18" TextWrapping="Wrap" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,168,0,0" />
     </controls:ImageButton>