非静态字段,方法或属性'system.windows.frameworkelement.width.get'需要对象引用

时间:2013-12-04 18:27:49

标签: wpf xaml

它在stackPanel.width stackPanel.height的wpf代码中给出了错误。 同样的错误是我的标题

XAML

        Page x:Class="Wpfhost.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="Page1">
     <Grid>
         <StackPanel Margin="0,0,0,0" Name="stackPanel" 
         HorizontalAlignment="Left" VerticalAlignment="Top" />
         </Grid>
      </Page>

它在stackPanel.width stackPanel.height的wpf代码中给出了错误。 同样的错误是我的标题

wpf

using System.Windows.Controls;
using System.Windows.Forms.Integration;
using WindowsFormsApplication1;

 namespace Wpfhost
 {
      /// <summary>
     /// Interaction logic for Page1.xaml
     /// </summary>
       public  partial class Page1 : Page
    {
         private readonly Form1 mainForm = new Form1();

         public Page1()
         {
            InitializeComponent();

             //Create a Windows Forms Host to host a form
             WindowsFormsHost windowsFormsHost = new WindowsFormsHost();

             StackPanel.Width = mainForm.Width;
             StackPanel.Height = mainForm.Height;
             windowsFormsHost.Width = mainForm.Width;
              windowsFormsHost.Height = mainForm.Height;

               mainForm.TopLevel = false;

               windowsFormsHost.Child = mainForm;

               StackPanel.Children.Add(windowsFormsHost);
    }
}

}

它在stackPanel.width stackPanel.height。

的wpf代码中给出了错误

1 个答案:

答案 0 :(得分:0)

在后面的代码中,您应该使用在XAML代码中创建的StackPanel实例。在您的情况下,它是stackPanelName="stackPanel"):

public Page1()
{
    InitializeComponent();

    //Create a Windows Forms Host to host a form
    WindowsFormsHost windowsFormsHost = new WindowsFormsHost();

    stackPanel.Width = mainForm.Width;
    stackPanel.Height = mainForm.Height;
    windowsFormsHost.Width = mainForm.Width;
    windowsFormsHost.Height = mainForm.Height;

    mainForm.TopLevel = false;  
    windowsFormsHost.Child = mainForm;  
    stackPanel.Children.Add(windowsFormsHost);
}