简体   繁体   中英

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?

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM