0

如何将包含图形的类添加到网格类中?目前我在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);
    }
}
}

包含图形的第二类

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);
        }
    }
}

错误:

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?)
4

1 回答 1

2

该类UserControl或其基类不包含该方法,正如编译器错误告诉您的那样。在编写代码时,当方法没有出现在 Intellisense中时,您还可以注意到类似的情况。键入时,您可能会立即得到一条红色的波浪线。

CreateGraphics是 Windows 窗体。但是您正在使用 WPF。这两个是具有不同类(具有不同方法)的不同 UI 框架。您是否不小心创建了 WPF 自定义控件库但想要创建 Windows 窗体控件库?

在 XAML 文件中为您的控件尝试这样的操作:

<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>

或者,您可以覆盖OnRender以提供自定义绘画。

于 2012-05-31T06:56:02.567 回答