本文介绍了确定在 WPF Grid 上单击了哪个单元格的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 3x3 矩阵网格.如果用户在特定单元格上,如何在点击后识别单元格坐标?
I have a 3x3 matrix grid. If a user on particular cell, how can I identify the cell cordinates after click?
请指教.谢谢PJ
推荐答案
假设你正在设计一个井字游戏,并且有问题的网格是标准的 WPF 网格,我想你会是最好在每个单独的单元格中放置一个控件.这样你就可以挂钩每个鼠标事件,如下所示:
Assuming you're designing a tic-tac-toe style game, and the grid in question is the standard WPF Grid, I'd imagine you'd be best putting a control in each separate cell. That way you can hook into mouse events for each, like so:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Column="0" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="0" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="0" Grid.Row="2" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="2" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="2" Click="ButtonClick" />
</Grid>
</Window>
在你的代码隐藏中:
private void ButtonClick(object sender, RoutedEventArgs e)
{
Button _btn = sender as Button;
int _row = (int)_btn.GetValue(Grid.RowProperty);
int _column = (int)_btn.GetValue(Grid.ColumnProperty);
MessageBox.Show(string.Format("Button clicked at column {0}, row {1}", _column, _row));
}
这篇关于确定在 WPF Grid 上单击了哪个单元格的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!