如何将矩形链接或引用到 Xaml 中的图像,以便在 C# 代码隐藏中进行访问

本文关键字:代码 访问 隐藏 图像 链接 Xaml 引用 | 更新日期: 2023-09-27 18:30:24

我在开发Windows通用应用程序时正在学习XAML/C#。

该程序允许将图像拖放到棋盘上,棋盘是一个有 8 行和 8 列的网格。每个网格单元格都有一个矩形和一个图像。拖放工作,将图像拖动到图像。在拖动开始事件和放置事件上,C# 代码隐藏获取图像源(在拖动开始事件上)和图像目标(在拖放事件上)。 源和目标都可用作开始拖动事件和丢弃事件的发送方参数。 这没有问题。 我还想在 C# 代码隐藏中访问与图像位于同一网格单元格中的矩形,如以下 XAML 代码所示。

有没有办法将属性添加到图像的 XAML 代码中,以引用同一网格单元格中的矩形?

<Rectangle Grid.Row="2" Grid.Column="0" Fill="{Binding Source={StaticResource queenModel0}, Path=Color, Mode=TwoWay}" />
<Image Name="Image0" Grid.Row="2" Grid.Column="0" Source="{StaticResource imageSource}" Tapped="OnImageTapped"  AllowDrop="True"
   CanDrag="{Binding Source={StaticResource queenModel0}, Path=HasQueen, Mode=TwoWay}"
   Opacity="{Binding Source={StaticResource queenModel0}, Path=Opacity, Mode=TwoWay}"
   DragEnter ="Image_DragEnter" DragLeave="Image_DragLeave" DragOver="Image_DragOver" DragStarting="Image_DragStarting" DropCompleted="Image_DropCompleted" Drop="DropQueen" />

如何将矩形链接或引用到 Xaml 中的图像,以便在 C# 代码隐藏中进行访问

我至少可以想到两种可能的方法:

选项#1:

按行/列索引检索Rectangle

int row = Grid.GetRow(sender), column = Grid.GetColumn(sender);
Rectangle rectangle = GetChildForRowColumn<Rectangle>(grid1, row, column);

哪里:

T GetChildForRowColumn<T>(Grid grid, int row, int column)
{
    foreach (Rectangle child in grid.Children.OfType<T>())
    {
        if (Grid.GetRow(child) == row && Grid.GetColumn(child) == column)
        {
            return child;
        }
    }
}

选项#2:

Tag 属性绑定到相关的Rectangle对象:

<Rectangle x:Name="rect20" Grid.Row="2" Grid.Column="0" Fill="{Binding Source={StaticResource queenModel0}, Path=Color, Mode=TwoWay}" />
<Image Tag="{x:Reference Name=rect20}" Name="Image0" Grid.Row="2" Grid.Column="0" Source="{StaticResource imageSource}" Tapped="OnImageTapped"  AllowDrop="True"
   CanDrag="{Binding Source={StaticResource queenModel0}, Path=HasQueen, Mode=TwoWay}"
   Opacity="{Binding Source={StaticResource queenModel0}, Path=Opacity, Mode=TwoWay}"
   DragEnter ="Image_DragEnter" DragLeave="Image_DragLeave" DragOver="Image_DragOver" DragStarting="Image_DragStarting" DropCompleted="Image_DropCompleted" Drop="DropQueen" />

然后在代码隐藏中:

Rectangle rectangle = (Rectangle)((FrameworkElement)sender).Tag;


可能还有其他方法可以完成相同的目标,但以上对我来说似乎是合理的。