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="<empty>"
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?