VS2012 - Add WPF existing user control to project

 ̄綄美尐妖づ 提交于 2019-12-23 12:59:41

问题


This seems like it should be pretty simple but I can't seem to make it happen. Lets say I have an existing project with a user control named uc1. I would like to use this user control in another project. I right-click the project name in the solution explorer and select add>existing item, change the drop down to all files and select the files uc1.xaml and uc1.xaml.vb. This of course adds the files to the project but there is no correlation between the xaml and the code behind file and there is no way to use the control. What is the proper way of doing this?


回答1:


This of course adds the files to the project but there is no correlation between the xaml and the code behind file and there is no way to use the control. What is the proper way of doing this?

Normally, you'd add a reference to the other project, and use the UserControl directly.

This allows you to build a single project with your UserControl, and use the resulting assembly (DLL) in multiple projects without duplicating the code.




回答2:


Reed's answer is a good architectural one. If you plan on creating a control that you will reuse in many projects then it's best to use a control library.

Your original question is valid in some situations though. Say you have some source code from the Internet that you've unzipped to your drive. This project contains a .XAML file and its linked .vb file that you want to add to a project.

As you seen, the Visual Studio Solution Explorer doesn't link the files when adding with the "Add Item" dialog. I think this is a bug. I find that if I reload the project, the affiliation is added.

Here's a workaround I use. I drag the files from Windows Explorer /File Explorer onto the project in Solution Explorer. That works correctly the first time.




回答3:


If you want to reuse your user controls you need to create a new project and choose "Class Library" from the list of available projects. When compiled this class library can easily be used by any number of other projects and solutions simply by adding a reference to compiled DLL created when you build this class library.

Edit: As mentioned in other answer it's "WPF UserControl Library", not simple "Class Library"...




回答4:


You just need to add the .xaml file and VS should auto add the code behind(nested). I've seen this not work a few times and as @Walt Ritscher said this is probably a bug.

I found simply restarting Visual Studio and reloading my solution worked.



来源:https://stackoverflow.com/questions/17072256/vs2012-add-wpf-existing-user-control-to-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!