2012-05-31 78 views
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?) 
+1

只是說有一個錯誤根本沒有幫助。 **你會得到哪個錯誤?即異常類型和StackTrace。 – Botz3000

+0

更新了錯誤。 – Hwang

回答

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提供風俗畫。