Grid.GetRow和Grid.GetColumn继续返回0

时间:2010-02-18 20:08:27

标签: wpf grid row

我有10x10 Grid。在每个空间中,我添加了一个标签,我添加了一个moused双击事件处理程序。因此,当我双击标签时,它应该显示RowColumn数字,但我只获得两个属性的0。

这是代码......(是的,我为每个标签设置了Grid.SetRowGrid.SetColumn

private void grid_Checked(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show(Grid.GetRow(e.Source as UIElement).ToString());
}

2 个答案:

答案 0 :(得分:3)

您确定所有内容都已正确连接吗?以下适用于我:

XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" MouseDown="Label_MouseDown">
        Label 0, 0
    </Label>
    <Label Grid.Row="0" Grid.Column="1" MouseDown="Label_MouseDown">
        Label 0, 1
    </Label>
    <Label Grid.Row="0" Grid.Column="2" MouseDown="Label_MouseDown">
        Label 0, 2
    </Label>
    <Label Grid.Row="1" Grid.Column="0" MouseDown="Label_MouseDown">
        Label 1, 0
    </Label>
    <Label Grid.Row="1" Grid.Column="1" MouseDown="Label_MouseDown">
        Label 1, 1
    </Label>
    <Label Grid.Row="1" Grid.Column="2" MouseDown="Label_MouseDown">
        Label 1, 2
    </Label>
    <Label Grid.Row="2" Grid.Column="0" MouseDown="Label_MouseDown">
        Label 2, 0
    </Label>
    <Label Grid.Row="2" Grid.Column="1" MouseDown="Label_MouseDown">
        Label 2, 1
    </Label>
    <Label Grid.Row="2" Grid.Column="2" MouseDown="Label_MouseDown">
        Label 2, 2
    </Label>
</Grid>

C#:

private void Label_MouseDown(object sender, MouseButtonEventArgs e)
{
    var label = e.Source as UIElement;
    var row = Grid.GetRow(label);
    var col = Grid.GetColumn(label);

    MessageBox.Show(string.Format("{0},{1}", row, col));
}

当我点击其中一个标签时,MessageBox包含正确的行和列。

答案 1 :(得分:1)

您可能需要使用e.OriginalSource而不是e.Source。作为路由事件的已检查事件将在路由树时更改e.Source