WPF TextBlock 点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13667066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF TextBlock Click Event
提问by Antarr Byrd
I have create textblocks in my grid in my wpf application. I know how to create the click event. But I'm not sure how to get properties from that cell. The properties I want Grid.Row and Grid.Column. How can I do this?
我在 wpf 应用程序的网格中创建了文本块。我知道如何创建点击事件。但我不确定如何从该单元格获取属性。我想要Grid.Row 和Grid.Column 的属性。我怎样才能做到这一点?
<Window x:Class="TicTacToe.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Tic-Tac-Toe" Height="356" Width="475">
<Grid VerticalAlignment="Top" ShowGridLines="True" Height="313" Margin="10,10,2,0">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="o" TextAlignment="Center" FontSize="72" FontFamily="Lucida Bright" FontWeight="Bold"></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" MouseLeftButtonDown="ChoosePosition" ></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="2" ></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" ></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" ></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="2" ></TextBlock>
<TextBlock Grid.Row="2" Grid.Column="0" ></TextBlock>
<TextBlock Grid.Row="2" Grid.Column="1" ></TextBlock>
<TextBlock Grid.Row="2" Grid.Column="2" ></TextBlock>
</Grid>
</Window>
private void ChoosePosition(object sender, MouseButtonEventArgs e)
{
}
回答by Daniel Castro
As Grid.Row and Grid.Column are attached properties from the Grid class, you can get them using this syntax:
由于 Grid.Row 和 Grid.Column 是 Grid 类的附加属性,您可以使用以下语法获取它们:
int row = Grid.GetRow(myTextBox);
int column = Grid.GetColumn(myTextBox);
In your case, you can cast the sender argument in the Click handler, so it would look like this:
在您的情况下,您可以在 Click 处理程序中转换 sender 参数,因此它看起来像这样:
var myTextBox = sender as TextBox;
if(myTextBox != null) {
int row = Grid.GetRow(myTextBox);
int column = Grid.GetColumn(myTextBox);
}
回答by BlokeTech
Have you checked the senderparameter? That will give you a reference to the textbox object which might be all you need depending on what you are trying to do.
你检查sender参数了吗?这将为您提供对文本框对象的引用,这可能是您所需要的,具体取决于您要执行的操作。
回答by Serhii Hrabas
Just change TextBox to TextBlock
只需将 TextBox 更改为 TextBlock

