Hi everyone,
I want to detect the controls under a point in UWP. whenever i tap on my application anywhere, the coordinates of the point will tell the controls under that point.
I used the below code in the code behind file of xaml-
private void Rectangle_Tapped(object sender, TappedRoutedEventArgs e)
{
var point = e.GetPosition(this);
var elements = VisualTreeHelper.FindElementsInHostCoordinates(point,grid);
}
the variable point is giving me the (x,y) coordinates, but the variable elements is giving the null value. what am i doing wrong, Please somebody tell me correct solution.
var elements = VisualTreeHelper.FindElementsInHostCoordinates(point,grid); - In this line the last word "grid" is the name property of "Grid" UIElement.
Below is my xaml code-
<Page
x:Class="NewTask.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:NewTask"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Name="grid" Tapped="Grid_Tapped">
<Grid Width="240" Height="100">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="A" Click="Button_Click" HorizontalAlignment="Center"></Button>
<Button Grid.Column="1" Content="B" HorizontalAlignment="Center"></Button>
<Button Grid.Column="2" Content="C" HorizontalAlignment="Center"></Button>
<Rectangle Name="rectangle" Grid.ColumnSpan="3" Opacity="0.5" Fill="Transparent" Stroke="White" Tapped="Rectangle_Tapped"></Rectangle>
</Grid>
</Grid>
</Page>
Below is my code behind file of xaml -
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
//UIElement grid = new Grid();
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(BlankPage1));
}
private void Rectangle_Tapped(object sender, TappedRoutedEventArgs e)
{
var point = e.GetPosition(this);
var elements = VisualTreeHelper.FindElementsInHostCoordinates(point,grid);
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
var point = e.GetPosition(this);
}
}