在 WPF 中使用类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16455001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a class in WPF
提问by Sturm
When I'm developing a ConsoleApp there is no problem to use classes in my Main that I've created in separated files (Project Menu --> Add Class). But later, when I try to do it in WPF that class is not recognized. I have made sure that the namespace it's the same both in my "MainWindow.xaml.cs" and my Class Canal.cs. When I define that same class but insideMainWindow.xaml.cs everything works fine, but due to the extension of the code I prefer separate it.
当我开发 ConsoleApp 时,在我的 Main 中使用我在单独文件(项目菜单 --> 添加类)中创建的类没有问题。但是后来,当我尝试在 WPF 中执行此操作时,无法识别该类。我已经确保在我的“MainWindow.xaml.cs”和我的 Canal.cs 类中的命名空间是相同的。当我定义同一个类但在MainWindow.xaml.cs 中时,一切正常,但由于代码的扩展,我更喜欢将它分开。
MainWindow.xaml.cs:
主窗口.xaml.cs:
//using
namespace Tcomp
{
public partial class MainWindow : Window
{
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ //Stuff but I can't use class created outside of MainWindow.xaml.cs
}
}
}
Canal.cs
运河.cs
//using
namespace TComp
{
public class Canal
{ //some propreties here
}
}
Thanks.
谢谢。
回答by mark vanzuela
Create the class inside a library project not on a console app. And on your WPF project, add a project reference to the library project you have created.
在库项目中创建类,而不是在控制台应用程序上。在您的 WPF 项目上,添加对您创建的库项目的项目引用。
回答by Alexander Bell
@mcxiand already answered your question. I would like to add another option: you can use a
@mcxiand 已经回答了您的问题。我想添加另一个选项:您可以使用
public partial class MainWindow : Window
and add it to as many files as you want containing your code, thus there will be no need to create additional class library. The key word here is partial, which allows the code encapsulated in this class to spread over multiple files (.cs).
并将其添加到包含代码的任意数量的文件中,因此无需创建额外的类库。这里的关键词是partial,它允许封装在这个类中的代码分布在多个文件(.cs)中。
回答by Alexandru Dicu
You must either instantiate the Canal class:
您必须实例化 Canal 类:
var myClass = new Canal();
and then you can use the properties from it. Make myClass a private member of your MainWindow.xaml.cs and you can access it anytime. Or the second way, make Canal class static and then you can access it from everywhere. Hope this helps.
然后你可以使用它的属性。将 myClass 设为 MainWindow.xaml.cs 的私有成员,您可以随时访问它。或者第二种方法,让 Canal 类成为静态,然后你就可以从任何地方访问它。希望这可以帮助。

