[XNA+Silverlight in WP7]如果WP7在XNA上使用Silverlight控制項時,ActualWidth與ActualHeight一值都是0時…

  • 2328
  • 0
  • 2012-02-25

1. 請先宣告全域變數
FrameworkElement element;2. 然後在程式進入點中加入(例如public GamePage()、public Main())

1. 請先宣告全域變數

FrameworkElement element;

2. 然後在程式進入點中加入(例如public GamePage()、public Main())

element = Application.Current.RootVisual as FrameworkElement; 
LayoutUpdated += new EventHandler(????_LayoutUpdated);

 

 

 

3. 在產生出來的????_LayoutUpdated中加入下列程式碼,跟一般程式碼不一樣的地方是,我們的ActualWidth與ActualHeight

是要從element裡面取得,如果是直接打上ActualWidth與ActualHeight有時候會取不到值。
 
 void ????_LayoutUpdated(object sender, EventArgs e)
        {
            
            // Verify the page has a valid size
            if (element.ActualWidth <= 0 && element.ActualHeight <= 0)
            {
                return;
            }

	
            int width = (int)element.ActualWidth;
            int height = (int)element.ActualHeight;

	
            // See if the UIElementRenderer is already the page's size
            if ((elementRenderer != null) &&
                (elementRenderer.Texture != null) &&
                (elementRenderer.Texture.Width == width) &&
                (elementRenderer.Texture.Height == height))
            {
                return;
            }

	
            // Dispose the UIElementRenderer before creating a new one
            if (elementRenderer != null)
            {
                elementRenderer.Dispose();
            }

	
            elementRenderer = new UIElementRenderer(this, width, height);
        }

 

 

 

4.最後就在OnDraw裡面加入下面code把控制項畫出來

 private void OnDraw(object sender, GameTimerEventArgs e)
 {

	
            //清除螢幕
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
           //將XNA控制項轉乘2D圖形
            elementRenderer.Render();
           //畫在螢幕上
            spriteBatch.Begin(); 
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
}

 

 

 

注意的地方是下方這兩個的true與False對不對;

SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

protected override void OnNavigatedTo(NavigationEventArgs e)
{
            
            // 設定圖形裝置的共用模式,以開啟 XNA 呈現
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);
           // GraphicsDeviceManager graphics;
       

            // 建立可用來繪製紋理的新 SpriteBatch。
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
          
            // TODO: 在此處使用 this.content 載入遊戲內容

            // 啟動計時器1
            timer.Start();
            
            base.OnNavigatedTo(e);
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
            // 停止計時器
            timer.Stop();
            
            // 設定圖形裝置的共用模式,以關閉 XNA 呈現
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
 }