我有一個網格,並且知道用鼠標點擊的位置的X值和Y值。從X和Y獲取網格行和列位置
例如:X:235,Y:235 - >這應該是在列:3和行:3
我怎麼什麼列和行是對X,Y座標?
我是否真的需要添加行/列的每個寬度,直到達到所需的x/y值?
我使用WPF(我的網格)& C#(爲X & y位置)
任何人可以幫助我嗎?
我有一個網格,並且知道用鼠標點擊的位置的X值和Y值。從X和Y獲取網格行和列位置
例如:X:235,Y:235 - >這應該是在列:3和行:3
我怎麼什麼列和行是對X,Y座標?
我是否真的需要添加行/列的每個寬度,直到達到所需的x/y值?
我使用WPF(我的網格)& C#(爲X & y位置)
任何人可以幫助我嗎?
對於這個請大家考慮......
Transparent
會做)。這是用於命中測試(鼠標點擊空白網格區域)的工作。GridSplitter
本身是網格中的成員。這一點很重要,因爲單擊網格分離器也會顯示網格分離器所在的相應單元索引(列,行)。ColumnSpan
和RowSpan
。XAML ...
<Window x:Class="WpfApplication3.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>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Mouse.PreviewMouseDown="Grid_MouseDown"
Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<GridSplitter ResizeDirection="Rows"
Width="{Binding ActualWidth,
RelativeSource={RelativeSource
AncestorType=Grid}}"
Height="4" Grid.ColumnSpan="3"
Background="Red" Grid.Row="1" />
<TextBox Height="60" AcceptsReturn="True"
Text="Element1"
ScrollViewer.VerticalScrollBarVisibility="Visible" />
<Button Content="Element2" Grid.Column="1"/>
<TextBlock Text="Element4" Grid.Row="2" Width="100"
Height="40" HorizontalAlignment="Left"
VerticalAlignment="Center"/>
<ComboBox SelectedIndex="0" Height="20"
Grid.Column="1" Grid.Row="2">
<ComboBoxItem Content="Element5"/>
</ComboBox>
<CheckBox Content="Element3" Grid.Column="2"/>
<RadioButton Content="Element6" Grid.Row="2"
Grid.Column="2" VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>
<StackPanel Orientation="Horizontal" Grid.Row="1">
<TextBlock Text="Selected Column and Row is ... " Margin="5"/>
<TextBlock x:Name="StatusTextBlock" FontSize="12"
FontWeight="SemiBold" Margin="5"/>
</StackPanel>
</Grid>
</Window>
代碼隱藏..
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
int selectedColumnIndex = -1, selectedRowIndex = -1;
var grid = sender as Grid;
if (grid != null)
{
var pos = e.GetPosition(grid);
var temp = pos.X;
for (var i = 0; i < grid.ColumnDefinitions.Count; i++)
{
var colDef = grid.ColumnDefinitions[i];
temp -= colDef.ActualWidth;
if (temp <= -1)
{
selectedColumnIndex = i;
break;
}
}
temp = pos.Y;
for (var i = 0; i < grid.RowDefinitions.Count; i++)
{
var rowDef = grid.RowDefinitions[i];
temp -= rowDef.ActualHeight;
if (temp <= -1)
{
selectedRowIndex = i;
break;
}
}
}
StatusTextBlock.Text = selectedColumnIndex + ", " + selectedRowIndex;
}
敢肯定,你必須做數學題。聽起來像一個網格擴展方法的工作。 – kenny
@Kenny這就是我現在要做的xD – Zarkos