dingoglotz
dingoglotz

Reputation: 2813

WPF Canvas Create object

I am using WPF and C# and I have a canvas with rectangles on it (like a maze). Now i want to create a character who moves (with the help of an algorithm) through this maze. Therefore I created a new class called character, but my problem starts here: How do I create an object on the canvas which has an image, a position and which can access the methods and attributes from the character-class? So the final thing should look like this:

private class MainWindow
{

   //Here the canvas is made visible and the rectangles are being drawn on the canvas

   //Then a method should start to create the character and move him through the maze

   //it should look like (character.move(1) so the character moves one step forward etc.)

}

private class Character
{
//here are the methods and attributes the character should have
}

Thanks in advance and sorry for my bad english :)

Upvotes: 2

Views: 1361

Answers (2)

Devendra D. Chavan
Devendra D. Chavan

Reputation: 8991

The first step would be to define the properties and the methods for the Character class. This would include (as you have indicated in the question) a Move(Position newPosition) method. Position can be a wrapper over the Pointstructure. The Character class also needs to contain a reference to the Canvas in which the character is present. This is required since when you call 'character.Move(position)`, the character can be moved in the canvas that the character is current associated with.

Furthermore, the MainWindow can contain a reference to the character or a collection of characters (in case your requirement if for multiple characters). The actual creation can be during the initialization of the MainWindow or can be lazy. Post initialization, your algorithm can work on the character instance.

Upvotes: 1

ianschol
ianschol

Reputation: 686

If you look at the problem from the opposite direction, it's much easier to solve.

Create your character object, hook it up so that everything works as you expect in your data (model). Then, you'll want to add properties that represent the location of the character, such as

public int XCoordinate { get; set; }
public int YCoordinate { get; set; }

Make sure the movement is done model-side. If you try to drive movement based on the visual display, it will over complicate the program.

Next, define the view of the character in your canvas, something like this:

<Canvas ...>
    <Image Canvas.Left="{Binding XCoordinate}" Canvas.Top="{Binding YCoordinate}" .../>
</Canvas>

Last, make sure your binding syntax is correct (did you set the DataContext?) and be sure to set up NotifyPropertyChanged to taste (both of these are well-covered elsewhere). Then you will be set up with a neatly divided model and view, and it should be much easier to focus on movement logic or whatever else you should desire.

Upvotes: 3

Related Questions