Fernando Sousa
Fernando Sousa

Reputation: 15

Clicking on a grid - UWP App

I am develop an new UWP app, and I have a grid:

<Grid.ColumnDefinitions>
       <ColumnDefinition Width="*" />
       <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
       <RowDefinition Height="*" />
       <RowDefinition Height="*" />
</Grid.RowDefinitions>

My table has 2 rows and 2 columns. In each row and column I have an image, and some textblocks. I would like that when click in each cell (for example when click on line 0 and column 0 of my grid) go to a XAML page.

How do I make my table cells clickable?

Upvotes: 1

Views: 3731

Answers (2)

Brett
Brett

Reputation: 56

Put a button in each cell of the grid and set the content of the button to an image. With the button you can use the click event to navigate to another xaml page.

<UserControl.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>

<Button Content="{StaticResource MyImage}" />

With a textblock you could do something like this.

<Button>
  <StackPanel>
    <TextBlock>My text here</TextBlock>
    <Image Source="some.jpg" Stretch="None" />
  </StackPanel>
</Button>

Upvotes: 0

Martin Zikmund
Martin Zikmund

Reputation: 39072

The Grid itself is just a layout control and on itself it will not tell you which cell was clicked, you can only know it's area was clicked.

What you can do is to put some controls in the cells (in this case ideally a Button) and set a Click or Tapped of those:

<Grid>
   <Grid.ColumnDefinitions>
           <ColumnDefinition Width="*" />
           <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
           <RowDefinition Height="*" />
           <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Grid.Column="0" Grid.Row="0"
                   Click="FirstCellClicked" />
    ...
 </Grid>

If you want something more subtle, you could use a Rectangle instead of the Button, set its Fill to Transparent (so that it captures user input) and then use it's Tapped event to handle the click.

<Grid>
   <Grid.ColumnDefinitions>
           <ColumnDefinition Width="*" />
           <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
           <RowDefinition Height="*" />
           <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="Transparent" Grid.Column="0" Grid.Row="0"
                   Tapped="FirstCellTapped" />
    ...
 </Grid>

Upvotes: 2

Related Questions