0

I'm trying to get the row and column placement from controls generated and placed in code from a ControlTemplate.

The ControlTemplate looks like this:

<Window.Resources>
        <ControlTemplate x:Key="myButtonTemplate" TargetType="Button">
            <Canvas x:Name="myButton" Background="#FFCFCECE" AllowDrop="True"
                    Drop="myButton_Drop" Opacity="1" MouseDown="myButton_MouseDown" >
                <Button x:Name="childButton" 
                        Height="30" Width="30" 
                        Canvas.Top="10" Canvas.Right="10" BorderThickness="0" >
                    <Button.Background>
                        <ImageBrush ImageSource="Resources/pic.png"/>
                    </Button.Background>
                </Button>
                <Label x:Name="nameLabel" Content="&lt;empty&gt;" 
                       Canvas.Bottom="35" Canvas.Left="10" FontSize="18" FontWeight="Bold" />
            </Canvas>
        </ControlTemplate>
</Window.Resources>

As you can see it has a method for accepting mouseclicks: myButton_MouseDown

And the controls are placed in the grid at startup like this:

// Add a button for every grid
for (int r = 0; r < myGrid.RowDefinitions.Count; r++)
{
    for (int c = 0; c < myGrid.ColumnDefinitions.Count; c++)
    {
        Button someButton = new Button();
        someButton.Template = (ControlTemplate)FindResource("myButtonTemplate");
        someButton.Name = "sb_" + r + "_" + c;
        someButton.SetValue(Grid.RowProperty, r);
        someButton.SetValue(Grid.ColumnProperty, c);
        myGrid.Children.Add(someButton);
     }
}

I am trying to get the position on where the grid was clicked, but I can't figure it out. This is the closest I've come, but row and col is always 0.

private void soundButton_MouseDown(object sender, MouseButtonEventArgs e)
{
    Canvas canvas = (Canvas)sender;
    int col = Grid.GetColumn((UIElement)canvas);
    int row = Grid.GetRow((UIElement)canvas);
}

Any suggestions on what I'm doing wrong?

ringkjob
  • 193
  • 2
  • 13
  • 2
    Closed. See my answer In the duplicated question for an example of how to implement this using well-known, standard, generally accepted, recommended practices and patterns in WPF such as `ItemsControl`s, `DataBinding`, and `DataTemplate`s. – Federico Berasategui Aug 04 '14 at 19:14

1 Answers1

1

Try this

private void myButton_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Canvas canvas = (Canvas)sender;
        int col = Grid.GetColumn((UIElement)canvas.TemplatedParent);
        int row = Grid.GetRow((UIElement)canvas.TemplatedParent);
    }
yo chauhan
  • 12,079
  • 4
  • 39
  • 58