Skip to main content
 首页 » 编程设计

c#之从其他类访问 MainWindow 属性

2024年02月24日15mfrbuaa

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

(这看起来很初级,但我是 C# 和 WPF 的新手)

请您参考如下方法:

您一定缺少命名空间。你可以这样做:


主窗口.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!"; 
        } 
    } 
} 

其他文件.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_); 
            } 
        } 
} 

请注意,我在每个文件中使用了相同的命名空间,并且通过使用 internal 关键字,消息可以被任何东西访问,只要它在相同的命名空间中。希望对您有所帮助!