Grid.GetRow and Grid.GetColumn keep returning 0

2019-07-15 10:59发布

I have a 10x10 Grid. And in each space I have added a label to which I added a mousedoubleclick event handler. So when I double click the label it's supposed to show the Row and Column number, but I only get 0 for both properties.

This is the code... (and yes I have set Grid.SetRow and Grid.SetColumn for each label)

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

标签: wpf grid row
2条回答
Ridiculous、
2楼-- · 2019-07-15 11:27

You may need to use e.OriginalSource instead of e.Source. The checked event, being a routed event, will change e.Source as it routes through the tree.

查看更多
家丑人穷心不美
3楼-- · 2019-07-15 11:33

Are you sure that everything is hooked up correctly? The following works for me:

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

The MessageBox contains the correct row and column when I click on one of the labels.

查看更多
登录 后发表回答