简体   繁体   中英

WPF TextBlock Click Event

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?

<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:

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:

var myTextBox = sender as TextBox;
if(myTextBox != null) {
   int row = Grid.GetRow(myTextBox);
   int column = Grid.GetColumn(myTextBox);
}

Have you checked the sender parameter? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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