0

I'm trying to create simple snake game in C# using WPF. I have multiple user controls. In the first user control I have a list of players. You pick a player and click a select button. After you click this button second user control is shown. This user control contains button to start a snake game.

The problem is that all user controls are created when you run the application but command that is bind to button that strat a snake game is created after you click the select button. Now if you click the start a snake game button the command is not executed. My question is: Does the command object has to exist before the user control is created or is there a way to notify the user control that command has been created?

  • No, there is no need to have it created before the user control is created, however the path that it binds to should notify any observers when it got created. If you add some more code, then you might have a higher chance of a meaningful answer :) – Icepickle Feb 12 '17 at 11:28

2 Answers2

0

you should try to implement the INotifyPropertyChanged interface on your command. It notifies the control about changes of the binded property. Have a look here, there is an example for the "FirstName" property.

Community
  • 1
  • 1
Markus
  • 66
  • 4
0

You need to return an actual command, so it must exist, but you can always create it if it doesn't. For example have the property 'getter' make sure the command exists before returning it:

private ICommand myThing;
public ICommand MyThing
{
    get
    {
        if (myThing == null)
        {
            myThing = new MyCommand(myArgs);
        }
        return myThing;
    }
}

Alternatively if you're running C# 6 then you can initialise the command at the auto-property declaration:

public ICommand MyCommand { get; } = new MyCommand(myArgs);
LordWilmore
  • 2,829
  • 2
  • 25
  • 30