单击网格 - UWP App

Clicking on a grid - UWP App

我正在开发一个新的 UWP 应用程序,我有一个网格:

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

我的 table 有 2 行和 2 列。在每一行和每一列中,我都有一个图像和一些文本块。我希望在单击每个单元格时(例如单击网格的第 0 行和第 0 列时)转到 XAML 页面。

如何使我的 table 单元格可点击?

Grid 本身只是一个布局控件,它不会告诉您单击了哪个单元格,您只能知道它的区域被单击了。

您可以在单元格中放置一些控件(在本例中最好是 Button)并设置其中的 ClickTapped

<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>

如果你想要更微妙的东西,你可以使用 Rectangle 而不是 Button,将其 Fill 设置为 Transparent(以便它捕获用户输入) 然后使用它的 Tapped 事件来处理点击。

<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>

在网格的每个单元格中放置一个按钮,并将按钮的内容设置为图像。通过按钮,您可以使用点击事件导航到另一个 xaml 页面。

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

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

使用文本块,您可以执行类似的操作。

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