访问其他类的MainWindow属性

访问其他类的MainWindow属性

问题描述:

我可以在WPF应用程序的MainWindow.xaml.cs文件中轻松修改/访问控件和MessageBox。但是,当我创建一些文件夹并在其中添加类时,我无法再访问MessageBox,也无法在Intellisense下拉列表中看到控件名称。访问其他类的MainWindow属性

(这似乎很基本的,但我是新的C#和WPF)

贵班有,使用的语句将允许您访问您正试图将类来访问新类中正确的你创建?

您必须缺少名称空间。你可以做这样的事情:


MainWindow.cs:

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

namespace YourNameSpaceHere 
{ 
    public partial class MainWindow : Window 
    { 
     internal static string message_ = string.Empty; 
     MainWindow() 
     { 
      InitializeComponent(); 
      SetupMessage(); 
     } 

     private void SetupMessage() 
     { 
      message_ = "Hello World!"; 
     } 
    } 
} 

OtherFile.cs:

using System; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; //are you missing this namespace? 
namespace YourNameSpaceHere 
{ 
     public class Messaging 
     { 
      Messaging() 
      { 
       MessageBox.Show(MainWindow.message_); 
      } 
     } 
} 

请注意,我在每个文件中使用相同的命名空间,并且只要它位于相同的命名空间中,就可以通过使用内部关键字来访问任何消息。我希望这有帮助!

+0

我也遇到过这个问题,并使用了部分的答案。我错过了下面的命名空间:using System.Windows.Controls;另外,你需要像使用Partial的例子那样使用'internal'关键字。 – tone7 2011-09-17 09:22:07