Andrew
Andrew

Reputation: 545

Dynamically Creating Image - Does not Exist in Current Context

I am trying to create a WhackaMole game in WPF in C#. I am a bit of a noob. In the for loop I am trying to add the number of "i" to the "Image". I get the following error:

 "Error The name 'Image1' does not exist in the current context" 

same thing for 'Image2' and so on. I am trying to integrate the images into a StackPanel.

Thanks for the help :)

    public partial class MainWindow : Window
    {
        Image[] ImageArray = new Image[50];
        public MainWindow()
        {
            Moleini = MoleScore[1];
            InitializeComponent();
            //string ImageName = "Image";
            for (int i = 0; i <= 8; i++)
            {
                Image Image = new Image();
                ImageArray[i] = Image;
                Image.Name = "Image" + i.ToString();
            }

            ////Create Images
            //for (int i = 0; i <= 8; i++)
            //{
            //    StackPanel1.Children.Add(CreateImage(i));
            //}

            //Dispacher for Mole to Appear
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Start();

            //Dispacher for Full Game Time
            System.Windows.Threading.DispatcherTimer endGame = new System.Windows.Threading.DispatcherTimer();
            endGame.Tick += new EventHandler(endGame_Tick);
            endGame.Interval = TimeSpan.FromSeconds(5);
            endGame.Start();
        }

        ////Create Image
        //public Image CreateImage(int i)
        //{

        //}

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {

            //Random Number Generator
            Random rnd = new Random();
            int num = rnd.Next(1, 9);

            //If Random Number is "1" Then Image will display
            if (num == 1)
            {
                ImageSource MoleImage = new BitmapImage(new Uri(ImgNameMole));
                Image1.Source = MoleImage;            
            }
            //If Random Number does not equal 1
            if (num != 1)
            {
                ImageSource hole = new BitmapImage(new Uri(ImgHole));
                Image1.Source = hole;
            }

            //If Random Number is "2" Then Image will display
            if (num == 2)
            {
                ImageSource MoleImage = new BitmapImage(new Uri(ImgNameMole));
                Image2.Source = MoleImage;
            }
}

Upvotes: 1

Views: 1646

Answers (4)

Rachel
Rachel

Reputation: 132618

Have you considered using the MVVM design pattern for your game? It's better suited to WPF's technology as it keeps the data and UI layer separate, like WPF's XAML and Binding system does, and it would make this much easier.

I remember answering a similar question about a minesweeper game, so I'll start there.

Begin with creating your Mole objects. Moles have 3 properties: RowIndex, ColumnIndex, and IsUp property.

Now you need a template to draw your Mole objects. Create a DataTemplate for the local:Mole object, and draw it using your images. A DataTrigger can be used to draw a mole picture if IsUp=True, or a hole image if IsUp=False.

Now in your code-behind, create a list of Mole objects, and initialize their default values. This just means two loops that go through creating Mole objects, and setting their Row/Column index.

To draw the list, use an ItemsControl in XAML. Change the ItemsControl.ItemsPanelTemplate to a Grid, and bind the Grid.Row and Grid.Column properties of the ItemsControl.ItemContainerStyle to the RowIndex and ColumnIndex properties on your Mole object.

And last of all, start up a timer that randomly changes the IsUp property of of a random Mole object in the list with IsUp=false to true. When changing it to true, also kick off a 2nd timer that will change IsUp=false after a random amount of time.

Adding score should be fairly easy. Add a ICommand HitMoleCommand to the Mole object, which returns a RelayCommand that is enabled when IsUp=True, and do some logic there (calculate points, change IsUp=False and cancel timer, etc).

But anyways, Image1 is not a property of your MainWindow class, which is why you can't access it from your dispatcher code. Just creating an object and giving it a name does not store it as a property on the Window, like when you create an object and give it a name in the XAML before running the project. You need to store the image somewhere on the class to access it like that, such as in the ImageArray object.

And I see that you've found your answer in the time it took me to write this, but I'm posting it anyways because I strongly feel that if you're working with WPF, you really should at the very least understand the MVVM design pattern, even if you don't choose to use it :)

Upvotes: 4

Jasen
Jasen

Reputation: 14250

Unless you have omitted code, Image1 and Image2 have not been previously declared. Using these variables within the context of dispatcherTimer_Tick scope will result in a compile-time error.

I think you intended to reference the ImageArray instead.

// instead of this
Image1.Source = MoleImage;
// you want this
ImageArray[1].Source = MoleImage;

Upvotes: 2

Santosh Panda
Santosh Panda

Reputation: 7351

Use this updated code:

            private void dispatcherTimer_Tick(object sender, EventArgs e)
            {
                //Random Number Generator
                Random rnd = new Random();
                int num = rnd.Next(1, 9);

                //If Random Number is "1" Then Image will display
                if (num == 1)
                {
                    ImageSource MoleImage = new BitmapImage(new Uri(ImgNameMole));
                    ImageArray[1].Source = MoleImage;            
                }
                //If Random Number does not equal 1
                if (num != 1)
                {
                    ImageSource hole = new BitmapImage(new Uri(ImgHole));
                    ImageArray[1].Source = hole;
                }

                //If Random Number is "2" Then Image will display
                if (num == 2)
                {
                    ImageSource MoleImage = new BitmapImage(new Uri(ImgNameMole));
                    ImageArray[2].Source = MoleImage;
                }
    }

Upvotes: 1

Eric
Eric

Reputation: 19873

Image Image = new Image(); will probably lead to problem. You should consider using Image image = new Image(); , without the capital I on the variable name

Upvotes: 0

Related Questions