Hwang
Hwang

Reputation: 502

Adding object into grid

How can I add a class that contains graphics into a class of grid? Currently I have error on the CreateGraphics.

using System.Windows;
using System.Windows.Controls;

namespace Othello
{
class Board : Grid
{
    public Grid grid = new Grid();
    ColumnDefinition col;
    RowDefinition row;

    int boxesAmount = 8;
    int boxSize = 100;
    int i = 0;

    public Board()
    {
        grid.Width = boxSize * boxesAmount;
        grid.Height = boxSize * boxesAmount;
        grid.HorizontalAlignment = HorizontalAlignment.Left;
        grid.VerticalAlignment = VerticalAlignment.Top;
        grid.ShowGridLines = true;
        grid.Background = System.Windows.Media.Brushes.Green;

        for (i = 0; i < boxesAmount; i++)
        {
            // Create Columns
            col = new ColumnDefinition();
            grid.ColumnDefinitions.Add(col);

            // Create Rows
            row = new RowDefinition();
            grid.RowDefinitions.Add(row);
        }
        //Console.WriteLine(grid));
        this.Children.Add(grid);

        Chess chess = new Chess();
        grid.Children.Add(chess);
        Grid.SetColumn(chess, 0);
        Grid.SetRow(chess, 0);
    }
}
}

2nd Class that contains the graphics

using System;
using System.Drawing;
using System.Windows.Controls;

namespace Othello
{

    class Chess : UserControl
    {
        Graphics g;

        public Chess()
        {
            Console.WriteLine("load chess");

            g = this.CreateGraphics();
            g.DrawEllipse(Pens.Black, 30, 30, 50, 50);
            this.AddChild(g);
        }
    }
}

The Error:

error CS1061: 'Othello.Chess' does not contain a definition for 'CreateGraphics' and no extension method 'CreateGraphics' accepting a first argument of type 'Othello.Chess' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 0

Views: 508

Answers (1)

Botz3000
Botz3000

Reputation: 39600

The class UserControl or its base classes just doesn't contain the method, exactly as the compiler error tells you. You can also notice things like that when the method does not appear in Intellisense when writing Code. You probably immediately got a red squiggly line when typing that.

CreateGraphics is Windows Forms. But you are using WPF. Those two are different UI Frameworks with different classes (which have different methods). Did you accidently create a WPF Custom Control Library but wanted to create a Windows Forms Controls Library?

Try something like this in the XAML file for your control:

<UserControl x:Class="WpfApplication2.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Ellipse Stroke="Black" Margin="30"></Ellipse>
    </Grid>
</UserControl>

Alternatively, you could override OnRender to provide custom painting.

Upvotes: 2

Related Questions