【问题标题】:WPF TextBlock Click EventWPF TextBlock 点击事件
【发布时间】:2012-12-31 03:08:16
【问题描述】:

我在我的 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)
        {
        }

【问题讨论】:

  • 您必须将 textblox 放在网格的列/行中

标签: c# wpf grid visual-studio-2012 .net-4.5


【解决方案1】:

由于 Grid.Row 和 Grid.Column 是 Grid 类的附加属性,您可以使用以下语法获取它们:

int row = Grid.GetRow(myTextBox);
int column = Grid.GetColumn(myTextBox);

在您的情况下,您可以在 Click 处理程序中转换 sender 参数,所以它看起来像这样:

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

【讨论】:

    【解决方案2】:

    您检查过sender 参数吗?这将为您提供对文本框对象的引用,这可能是您所需要的全部内容,具体取决于您要执行的操作。

    【讨论】:

      【解决方案3】:

      只需将 TextBox 更改为 TextBlock

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        • 2018-06-29
        • 2011-03-08
        • 1970-01-01
        相关资源
        最近更新 更多