简体   繁体   English

WPF TextBlock单击事件

[英]WPF TextBlock Click Event

I have create textblocks in my grid in my wpf application. 我在wpf应用程序的网格中创建了文本块。 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. 我想要Grid.Row和Grid.Column的属性。 How can I do this? 我怎样才能做到这一点?

<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)
        {
        }

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);
}

Have you checked the sender parameter? 您检查sender参数了吗? That will give you a reference to the textbox object which might be all you need depending on what you are trying to do. 这将为您提供对文本框对象的引用,这取决于您要尝试执行的操作。

只需将TextBox更改为TextBlock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM