How can I connect xaml and xaml.cs files - c#

I had a VB projected and converted it to C# using online conversion tools. Now the problem is xaml and xaml.cs file do not connect to each other, that is they don't recognize their dependencies (Red area in Fig). Actually it should appear like Window1 Files (Green Area in the image.) How can I achieve this.
I am trying my hands on WPF so may be a layman sort of question.

This is simple, try to add in project existing items and select the XAML (not .cs, etc.) files in list of formats. In VS2010 thats helps.

If you cannot get the IDE to do it (Papa John's post), then you can do it by editing the project file.
That information is in the .csproj file (which is an XML file -- you can open it in a text editor, or by right-clicking on it, choosing "unload", and then opening it -- choose reload to load it up as a project again).
Here is the information to look for, you would need to add the "DependentUpon" tag.
<Compile Include="TheFile.xaml.cs">
<DependentUpon>TheFile.xaml</DependentUpon>
</Compile>

Easiest Way!!!
I came across the same. I got the way out. Here is how to get the .xaml.cs nested under the .xaml in Solution Explorer:
In Windows File Explorer (outside of Visual Studio), open the folder where the required files are.
Select both files (.xaml and .xaml.cs) together.
Drag it onto your project name in the Solution Explorer.
Its done! :)

Using a Xamarin PCL Solution:
1) Go to your PCL folder and open your MySolution.csproj file
2) There should be several groups of <ItemGroup> tags. One of them declares <EmbeddedResource> tags and another will contain, <Compile> <DependentUpon></DependentUpon></Compile> groups of tags.
3) For MyPage.xaml and MyPage.xaml.cs files to be linked, you must have a group of xmls that declare your xaml page.
<EmbeddedResource Include="MyPage.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
<Compile Include="MyPage.xaml.cs">
<DependentUpon>MyPage.xaml</DependentUpon>
</Compile>
Note that if your page is in a folder you should specify that like so:
<Compile Include="Views\MyPage.xaml.cs">
<DependentUpon>MyPage.xaml</DependentUpon>
</Compile>
<EmbeddedResource Include="Views\MyPage.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
Note that this works with OSX and Windows

Based on Kyle White's comment on the official Xamarin bug report 55591: .xaml files in .NETStandard library appear twice in solution explorer, I found a simple solution to this problem within the linked .NET Standard sample project by Oren Novotny
Within your .csproj file, add the following <ItemGroup>:
<ItemGroup>
<Compile Update="**\*.xaml.cs" DependentUpon="%(Filename)" />
<EmbeddedResource Include="**\*.xaml" SubType="Designer" Generator="MSBuild:UpdateDesignTimeXaml" LogicalName="%(Filename)%(Extension)" />
</ItemGroup>
Afterwards, all xaml files within the project structure will be displayed in the Solution Explorer window automatically - even if you'll ever add new xaml files.
How does this magic work?
The Compile element within the ItemGroup is using wildcards to iterate through all directories, searching for .xaml.cs files and marking them as dependent on the xaml files of the same name. Please note that this works only because the %(Filename) item metadata used for the DependentUpon element contains the left-most file extension, which matches the name of the xaml file by convention.
The EmbeddedResource element will include all xaml files to the project, so that they are visible within the Solution Explorer window while marking them as Designer files, and declaring that the UpdateDesignTimeXaml target defined within the Xamarin.Forms NuGet package should be used to generate code from the markup file.

Using Xamarin Shared Code solution:
1) Go to you project folder after unloading the shared project
2) Find the projitems file and edit that adding the DependentUpon tag as described in other answers above.
3) Save the file
4) Go back to visual studio and you should get a dialog that allows you to reload all or just open the project again.

An even easier and faster solution for Xamarin Forms projects, no need to touch csproj file at all, very quick fix.
Make sure you have Show All Files selected for solution explorer - it may be on by default.
Select all affected files
Right click > Exclude from Project
Select the same files again (should be faded out)
Right Click > Include in Project
They should now all be nested correctly and all the changes necessary to the .csproj file will be done.
You may have an InitializeComponent() does not exist in the current context) error after this.
If that's the case, the simple fix is..
Select all affected items and change Build Action from Page to Embedded Resource

I was able to just restart Visual Studio for Mac 2019 v16.2 and it reconnected my .xaml & .cs files that should've been connected.
If that doesn't work, Hitsa's solution worked for me as well on a separate occasion.

If you get the Nested File VS Extension, you can do this by right clicking similarly named files and choosing to "nest automatically" or you can nest manually.
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.FileNesting

In a Shared Project there is .shproj file instead of a .csproj file and the and items do not exist there.
However I found there is also a .projitems file and adding a section there as described above caused the .xaml and .cs files to be linked

The usual - Close Visual Studio, delete the vs folder in the root folder of your solution and reopen Visual Studio (2019) just worked for me.

For VS 2019, you have only to edit .csproj file and eliminate all references to .xaml.cs file
es:
<ItemGroup>
<Folder Include="Models\" />
<Folder Include="Services\" />
<Folder Include="ViewModels\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Views\MyPage.xaml">
<LogicalName>MyPage.xaml</LogicalName>
</EmbeddedResource>
</ItemGroup>

I found the problem was when i reloaded a github project from my menu, instead of the actual project file inside that local downloaded repo. Once I selected the .sln file it worked again!

Related

.NET Maui The name 'InitializeComponent' does not exist in the current context

I have created a ResourceDictionary file that comes with a .cs file. So afer creating the ResourceDictionary file I'm getting an error The name 'InitializeComponent' does not exist in the current context.
Below is the xaml file associated with the above file.
I'm using VS2022 17.5.0 Preview 1.0
I have set the build action for the c# file to C# Compiler
I have cleaned and rebuilt my project several times and tried deleting the bin and obj folders nothing seems to work
When I do Project / rt-click / Add / NewItem / .Net Maui ResourceDictionary (XAML), this is what gets added to .csproj:
<MauiXaml Update="Dictionary1.xaml">
<Generator>MSBuild:Compile</Generator>
</MauiXaml>
Note that the Compile is nested within the MauiXaml element; it is not a separate Item.
See if your .csproj has TWO separate Items, one for Dictionary1.xaml, another for Dictionary1.xaml.cs.
If so, replace those two items, with a combined item as shown above.
(For me, this builds without problem.)
In your case, the .csproj doesn't show MauiXaml BuildAction?
Replace:
<ItemGroup>
<None Include="Themes\Light.xaml" />
</ItemGroup>
with:
<ItemGroup>
<MauiXaml Update="Themes\Light.xaml">
<Generator>MSBuild:Compile</Generator>
</MauiXaml>
</ItemGroup>
I don't know whether this should be kept or removed:
<ItemGroup>
<Folder Include="Themes\" />
</ItemGroup>
Leave it in for now.
This sounds like a similar issue that often plagues Xamarin solutions. I think that there's an underlying bug, or delay in interpreting the files when displayed within Visual Studio.
Several options:
Make a small change to the file in question - even adding or deleting a space will do, save it and rebuild solution.
Clean the solution and rebuild.
Unload and reload project to which the files belong. (Right click on the project in Solution explorer window, select unload, then select load.
Xaml files may need to be set as embedded resource as their Build Action under their properties (again in Solution explorer).

Visual studio creates unusual files automatically when Press CTRL + S [duplicate]

My company uses a combination of some database tables, a web page front end and an "export" application to handle our string resources in our web sites.
The export application used to work just fine when we used VS2008, but since switching to VS2010 the resources now have a designer.cs file "beneath" them in the solution explorer.
The problem is that the "export" application only generates the .resx files and not the underlying designer.cs files.
So, is there a way to not have those designer.cs files, or alternatively some way to automatically re-generate (or even some command the export application could call to re-generate them)
I had a problem where VS 2010 would not regenerate the Designer.cs files, and couldn't find the solution elsewhere.
I was able to regenerate them though, without going to the command line.
To fix the issue in Visual Studio 2010 I did the following:
Deleted the Designer.cs file
Right clicked on the main resx file
Selected Run Custom Tool
That rebuilt the Designer.cs file.
Hope that might help someone else in the future..
From MSDN we have:
Compiling Resources into Assemblies
When you build your application, Visual Studio invokes the
resgen.exe tool to convert your application resources into an
internal
class called Resources. This class is
contained in the Resources.Designer.cs
file which is nested under the
Resources.resx file in Solution
Explorer. The Resources class
encapsulates all your project
resources into static readonly get
properties as a way of providing
strongly-typed resources at run-time.
When you build through the Visual C#
IDE, all the encapsulated resource
data, including both the resources
that were embedded into the .resx file
and the linked files, is compiled
directly into the application assembly
(the .exe or .dll file). In other
words, the Visual C# IDE always uses
the /resource compiler option. If you
build from the command line, you can
specify the /linkresource compiler
option that will enable you to deploy
resources in a separate file from the
main application assembly. This is an
advanced scenario and is only
necessary in certain rare situations.
If you prefer to automatically generate the *.designer.cs files from *.resx files when building the project, the following approach worked for us and it might work for you as well:
Close your solution
Open as an XML file the project file in which you want to automatically generate the designer files. Note that you need to load it as an XML file. You can't edit these settings through the project property page.
Add a target to the project as follows:
<Target Name="GenerateDesignerFiles">
<Message Text="Deleting old Designer Files..."/>
<Delete Files="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).resources')"/>
<Delete Files="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).designer.cs')"/>
<Message Text="Generating Designer Files..."/>
<GenerateResource
Sources="#(EmbeddedResource)"
StronglyTypedLanguage="C#"
StronglyTypedClassName="%(Filename)"
StronglyTypedNamespace="#(EmbeddedResource->'%(CustomToolNamespace)')"
StronglyTypedFileName="#(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).designer.cs')"
PublicClass="true"
>
</GenerateResource>
<Message Text="Generating Designer Files complete."/>
</Target>
Locate the target named "BeforeBuild". This target may be commented out (the default).
Modify the "BeforeBuild" target as follows:
<Target Name="BeforeBuild">
<CallTarget Targets="GenerateDesignerFiles"/>
</Target>
This solution is based on all resource files being listed as "EmbeddedResource" within an ItemGroup of the project file, e.g.
<ItemGroup>
<EmbeddedResource Include="Resources\Creditor\Display_Creditor.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Display_Creditor.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.Creditor</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="Resources\InboundEmail\Tooltip_InboundEmailDetails.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Tooltip_InboundEmailDetails.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.InboundEmail</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="Resources\Creditor\Tooltip_CreditorDetails.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Tooltip_CreditorDetails.Designer.cs</LastGenOutput>
<CustomToolNamespace>Acme.Web.Resources.Creditor</CustomToolNamespace>
</EmbeddedResource>
</ItemGroup>
Disclaimer: This has been tested with Visual Studio 2013 and C# projects. It may or may not work for other projects and/or other versions of Visual Studio.
Try this:
Right click on resx file
Click on properties
Set the properties:
Copy to output Directory : Copy always
Custom tool : PublicResXFileCodeGenerator
Save and build again.
Problem solved.
Following these steps worked for me.
Delete your designer.cs file.
Click on properties
Out put directory - copy always.
Custom tool: PublicResXFileCodeGenerator
Save and build.
Right click on resx and
Click run custom tool.

Move code file under another file in project

I want to move one code file under the group of another, related file, like here:
As you see, SingleObjectViewModel.Commands.cs is hidden in SingleObjectViewModel.cs group. It can be useful in some cases.
I've created SingleDocumentViewModel.Commands.cs but simple drag-n-drop in Visual Studio do not work.
How to achieve it?
I found one way of doing this, but it is not user-friendly and needs to edit project file by hands. I'm not sure it will work in other versions of Visual Studio then mine (MS Visual Studio 2013)
First, unload project (right-click on project, Unload Project).
Then edit csproj file (right-click again, Edit *.csproj)
In editor, replace:
<Compile Include="SingleDocumentViewModel.Commands.cs">
with
<Compile Include="SingleDocumentViewModel.Commands.cs">
<DependentUpon>SingleDocumentViewModel.cs</DependentUpon>
</Compile>
Then save edited file and load project again (right-click on it, Reload project).
Now files are grouped:

Setting the Build Action for a folder in VS for a Win 8.1 app

In previous Windows 8 /8.1 projects, any images that I have added to a folder inside the Assets folder is automatically set to "Content" in the Build Action.
As a result, the images render when the project is built.
But our latest project seems to default to BundleResource, and after wasting time trying to work out why the image isn't rendering, I remember that I have to manually change each image to Content.
Does anyone know how to set the whole folder to Content so that newly added images will be Content by default? I don't know why this project is behaving differently to our previous ones. :-(
I had the same issue while ago. As far as I know is not possible to set Build Actions for folders on Visual Studio, only individual files.
The solution I've found is to edit Project.projitems manually (I mean, outside of VS and after it is closed, via another code editor) from:
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)Assets\example.json" />
<Content Include="$(MSBuildThisFileDirectory)Assets\NestedFolder\example.file" />
</ItemGroup>
to this:
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)Assets\**\*.*">
</ItemGroup>
Which will do the trick of setting everything under Assets as Build Action: Content, and will be able to see it mapped on Solution Explorer after restarting VS - or rebuilding files.
NOTE: Keep in mind that if you add anything to this folder via VS this rule could be overwritten. So, my advice is: once this rule is added, only add files directly to the folder.

In a .csproj file, what is <None Include="..."> for?

How is
<None Include="C:\foo.bar" />
different from
<Content Include="C:\foo.bar" />
?
The MSDN article on the build action property explains the differences.
None - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Content - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.
One difference is how they get published; "None" items don't get included in a publish, "Content" items do; for example, on the "Application Files" dialog on the Publish tab.
I am not 100% sure (I read the MSDN description of Build Action property) but just copying that answer from MSDN to StackOverflow does not answer the question completely for me.
The difference of None and Content only has an effect on Web projects. For a command line project, WinForm project or UnitTest project (in my case) etc. None and Content have no different behavior.
MSDN: "project output group" or "Content output group" only terms used in a Web project, right?
In my situation, my MSBuild file had an ItemGroup for image resources that appeared as follows:
<ItemGroup>
<Content Include="Resources\image001.png" />
<Content Include="Resources\image002.png" />
<Content Include="Resources\image003.png" />
<Content Include="Resources\image004.png" />
<None Include="Resources\image005.png" />
<None Include="Resources\image006.png" />
<None Include="Resources\image007.png" />
</ItemGroup>
While my project was building fine, this left me wondering why I had a mix of Content and None item type elements in my ItemGroup. This MSDN article (for Visual Studio 2010) gave me the guidance I was looking for:
Note that when the resource editor adds an image, it sets Build
Action to None, because the .resx file references the image
file. At build time, the image is pulled into the .resources file
created out of the .resx file. The image can then easily be accessed
by way of the strongly-typed class auto-generated for the .resx file.
Therefore, you should not change this setting to Embedded
Resource, because doing this would include the image two times in
the assembly.
Resolution: With this guidance, using a text editor, I changed the Content item type elements to None.
Also, for an overview of MSBuild items, see this MSDN article.
Content files are not included in a build, but are included in a publish.
None files are not included in a build or publish, unless they are configured that way by you. For instance, a "Copy to Output Directory" setting of "Always" or "Newer", will cause them to be included in both a build and publish.
I have a project that contains no compilable items (it stores html and javascript for jasmine unit tests).
One day my solution (that contained said project) stopped compiling saying "The target "Build" does not exist in the project".
I added an import to bring in the compiler, which worked fine on my machine but failed using msbuild on the build server.
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
I then changed a line from
<None Include="SpecRunner.html" />
to
<Content Include="SpecRunner.html" />
and it worked on the build server as well.
You need None in a template project file to include files you define in the .vstemplate otherwise they are lost in the creation & translation process. They get left behind in the temp folder it uses to build everything and then deleted shortly after.
In my case .Pubxml is one of those files among None list. It's not meant for solution building or as a static file for web project. But to publish the site to Azure, the configurations are present in this.
As per Microsoft article these are the major types we see among .csproj file tags:
None - The file is not included in the project output group and is not
compiled in the build process. An example is a text file that contains
documentation, such as a Readme file.
Compile - The file is compiled into the build output. This setting is
used for code files.
Content - The file is not compiled, but is included in the Content
output group. For example, this setting is the default value for an
.htm or other kind of Web file.
Embedded Resource - This file is embedded in the main project build
output as a DLL or executable. It is typically used for resource
files.

Categories

Resources