0
\$\begingroup\$

I have a bunch of images I'm using for a chess game in a canvas using wpf, xaml, and C#. I want to use

Canvas.SetTop(image, position);

to set the position of this image. However I am given the index of child in my canvas and that is it.

myCanvas.children[index]

I tried

Canvas.SetTop(myCanvas.children[index], position);

but that did not work. How can I change the position of the image given only the index of the image in the canvas?

Edit: Another option would be to change the position of the canvas child. But I couldn't find anything for that.

\$\endgroup\$
1
\$\begingroup\$

Since you're using WPF I expect you don't plan to use a lot of animation, so a better way to do this would be with a Grid:

<!-- XAML -->
<Grid x:Name="Board">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
</Grid>

To place something in a cell:

void SetPosition(UIElement element, int x, int y)
{
    if (!Board.Children.Contains(element))
        Board.Children.Add(element);
    Grid.SetColumn(element, x);
    Grid.SetRow(element, y);
}

You could also use a UniformGrid.

A completely data-driven answer can be found in StackOverflow: WPF controls needed to build chess application

| improve this answer | |
\$\endgroup\$
-1
\$\begingroup\$
myCanvas.Children[index].SetValue(Canvas.TopProperty, position);
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Although that line of code could be the solution for the OP, we like answers that actually explain why this is the missing code line and what it does. You can use the 'edit' feature to add more text. \$\endgroup\$ – Vaillancourt Sep 17 '16 at 3:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.