Using the C#/Win32 code generator to enhance your WinUI 3 app


With the new C#/WIn32 code generator it has become super easy to generate interop code for Windows APIs. Previously we had to go read the doc and figure out the proper C# signature, or browse pinvoke.net and hope it is covered there. We could also reference an external package like PInvoke.Kernel32, PInvoke.User32 etc. etc. but it would also pull in a lot more dependencies and APIs than you probably need.

Now with the code generator, it's as simple as adding the nuget package, and then add the method name you want to a "NativeMethods.txt" file, and you instantly have access to the method and any structs and enums you need. It also uses all the latest C#9 features for improved interop code.

You can read the full blogpost on this here: https://blogs.windows.com/windowsdeveloper/2021/01/21/making-win32-apis-more-accessible-to-more-languages/

 

Using the C# Win32 Interop Generator with WinUI 3

The latest WinUI 3 Preview 4 release does have several improvements around improving your window, but there is also a lot still missing. However most of those features can be added by obtaining the window's HWND handle and calling the native Win32 methods directly.

So let's set out to try and control our window using CsWin32.

 

First, we'll create a new WinUI Desktop project:

 

image

Next we'll add the Microsoft.Windows.CsWin32 NuGet package the project (not the package project!) to get the Win32 code generator. However, note that the current v0.1.319-beta version has some bugs that you'll see when WinUI is referenced. So instead we'll use the daily build which has been fixed (you can skip this if you're reading this and a new version has been published). Go edit the project file, and add the following to get the latest daily from the nuget server that hosts these builds: (also shout-out to Andrew Arnott for quickly fixing bugs as they were discovered)

  <PropertyGroup>
   <RestoreAdditionalProjectSources>https://pkgs.dev.azure.com/azure-public/vside/_packaging/winsdk/nuget/v3/index.json;$(RestoreAdditionalProjectSources)</RestoreAdditionalProjectSources>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.CsWin32" Version="0.1.370-beta">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

 

Next we'll add a new text file to the root of the project named NativeMethods.txt.

Screenshot 2021-02-19 100955

We're now set up to generate the required methods.


The first Win32 method we need is the ShowWindow method in User32.dll, so add the text ShowWindow to its own line in the NativeMethods.txt file.

Note that you should now be able to get auto completion and full intellisense documentation on the method Microsoft.Windows.Sdk.PInvoke.ShowWindow. Pretty cool huh?

Screenshot 2021-02-19 094339

If you use VS16.9+, you can also expand the Project Name -> Dependencies -> Analyzers -> Microsoft.Windows.CsWin32 -> Microsoft.Windows.CsWin32.SourceGenerator and see the code that gets generated.

Screenshot 2021-02-19 094156

None of this is coming from a big library. It's literally just an internal class directly compiled into your application. No external dependencies required, and if you're building a class library, no dependencies to force on your users either.

 

Controlling the WinUI Window

As you can see in the screenshot above, the first thing we need to do is provide an HWND handle. You can get this from the Window, but it's not obvious, as we need to cast it to an interface we define. Let's create a new static class called WindowExtensions to help us do this:

using System;
using System.Runtime.InteropServices;
using WinRT;

namespace WinUIWinEx
{
    public static class WindowExtensions
    {
        [ComImport]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        [Guid("EECDBF0E-BAE9-4CB6-A68E-9598E1CB57BB")]
        internal interface IWindowNative
        {
            IntPtr WindowHandle { get; }
        }

        public static IntPtr GetWindowHandle(this Microsoft.UI.Xaml.Window window)
            => window is null ? throw new ArgumentNullException(nameof(window)) : window.As<IWindowNative>().WindowHandle;
    }
}

 

Now we want to call the ShowWindow method. If you read the documentation for this method: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow you'll see takes a number indicating the desired window state, like 0 for hide, 3 for maximize, 5 for show, 6 for minimize and 9 for restore.

        private static bool ShowWindow(Microsoft.UI.Xaml.Window window, int nCmdShow)
        {
            var hWnd = new Microsoft.Windows.Sdk.HWND(window.GetWindowHandle());
            return Microsoft.Windows.Sdk.PInvoke.ShowWindow(hWnd, nCmdShow);
        }

        public static bool MinimizeWindow(this Microsoft.UI.Xaml.Window window) => ShowWindow(window, 6);
        public static bool MaximizeWindow(this Microsoft.UI.Xaml.Window window) => ShowWindow(window, 3);
        public static bool HideWindow(this Microsoft.UI.Xaml.Window window) => ShowWindow(window, 0);
        public static bool ShowWindow(this Microsoft.UI.Xaml.Window window) => ShowWindow(window, 5);
        public static bool RestoreWindow(this Microsoft.UI.Xaml.Window window) => ShowWindow(window, 9);

 

Because these are all extension methods, this now enables us to make simple calls inside our Window class like this:

       this.MaximizeWindow();

  

The CsWin32 code generator just makes this really easy. I've taken all of this a few levels further and started a WinUIEx project on GitHub, where you can see the above code and much more, like setting your windows to be always-on-top or adding a tray icon to your app, so you can minimize to the tray.

You can find the repo on github here:

https://github.com/dotMorten/WinUIEx/

Building custom XAML control panels

One of my favorite XAML Control primitives is the Panel class. It's what drives Grid, StackPanel, Canvas and many many other controls that contains a set of other controls, and controls layout the children out in the view.

So in my second twitch stream, I walked through creating a custom panel that lays out controls in a grid-like manner, without having to do all the row and column definitions. It mainly focuses on the Arrange and Measure steps in the layout life-cycle, which applies to both WPF, UWP and WinUI (or even Silverlight for that matter ;-). And just for fun I used the latest WinUI 3.0 Alpha release (but it really doesn't matter as the concepts are the exact same - only namespaces differs). 




And please subscribe to my YouTube and Twitch channels!

Compiling and debugging WPF

With WPF going open source it’s pretty awesome that we can no clone the code, tweak it, build it and debug right into a local copy of WPF. I see huge potential here, not just for getting bug fixes in, but for instrumenting WPF when you got those extra tricky bugs you’re trying to track down.

However, it was not simple at all to get this stuff working like that. Building it was easy, but I found it surprisingly hard to use the local build. Going back and forth with the WPF team (especially big shout-out to Steven Kirbach), I finally got it working, and already submitted a PR to update the developer documentation.

However I wanted to walk you through a quick step-by-step guide to doing this yourself. All commandline steps below are assumed to be done from the same folder (otherwise you’d have to adjust the paths)

First of all, this approach will not work with .NET Core 3.0.0-Preview6. You need the nightly Preview7, as bug in Preview 6 prevented this from working. Once Preview 7 ships, the extra Preview7-specific steps aren’t needed.

So first step go and download and install the nightly from https://github.com/dotnet/core-sdk (Get the Windows x64 Master installer).

Next open a command prompt and clone the WPF Repo (I assume you have Git installed already). Run the following command:

git clone https://github.com/dotnet/wpf

Now let’s make a small change to WPF we can later see once we get it running. For example, open wpf\src\Microsoft.DotNet.Wpf\src\WindowsBase\System\Windows\DependencyObject.cs and add the following to the DependencyObject constructor:

Debug.WriteLine("Dependency Object created : " + this.GetType().FullName);

This will cause the output window to show each dependency object getting created.

Next let’s build WPF:

wpf\build.cmd –pack

It’ll take a few minutes (especially the first time), and hopefully you won’t see any errors at the end.

OK next up let’s create a new WPF project we can use as a test, using the following command:

dotnet new wpf –o TestApp

This will create a subfolder named “TestApp”. Go into this folder and open up the TestApp.csproj file in Visual Studio. Right-click the project and select “Edit Project File” and add the following to the project below the existing property group:

  <PropertyGroup>
     <!-- Change this value based on where your local repo is located -->
     <WpfRepoRoot>..\wpf</WpfRepoRoot>
     <!-- Change based on which assemblies you build (Release/Debug) -->
     <WpfConfig>Debug</WpfConfig>
     <!-- Publishing a self-contained app ensures our binaries are used. -->
     <SelfContained>true</SelfContained>
    <!-- The runtime identifier needs to match the architecture you built WPF assemblies for. -->
    <RuntimeIdentifier>win-x86</RuntimeIdentifier>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="$(WpfRepoRoot)\artifacts\packaging\$(WpfConfig)\Microsoft.DotNet.Wpf.GitHub\lib\netcoreapp3.0\*.dll" />
    <ReferenceCopyLocalPaths Include="$(WpfRepoRoot)\artifacts\packaging\$(WpfConfig)\Microsoft.DotNet.Wpf.GitHub\lib\$(RuntimeIdentifier)\*.dll" />
  </ItemGroup>

The following steps are only necessary when using a nightly-build:

  • Save all and pick a place to save the .sln solution file (this step is important). Close Visual Studio and create a new text file “nuget.config”
  • Add the following to the nuget.config file:

<configuration>
  <packageSources>
    <add key="dotnet-core" value="https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" />
    <add key="dotnet-windowsdesktop" value="https://dotnetfeed.blob.core.windows.net/dotnet-windowsdesktop/index.json" />
    <add key="aspnet-aspnetcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore/index.json" />
    <add key="aspnet-aspnetcore-tooling" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore-tooling/index.json" />
    <add key="aspnet-entityframeworkcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-entityframeworkcore/index.json" />
    <add key="aspnet-extensions" value="https://dotnetfeed.blob.core.windows.net/aspnet-extensions/index.json" />
    <add key="gRPC repository" value="https://grpc.jfrog.io/grpc/api/nuget/v3/grpc-nuget-dev" />
  </packageSources>
</configuration>

Open the solution back up and build and run. With a little luck your app should launch and you’ll see something like this in the Output Window confirming our change made it (or course you can now also step right into source locally on disk):

Annotation 2019-06-20 213538

First release of WindowsStateTriggers

With the release of the Windows 10 Universal SDK today I’ve updated the Github Repository for the WindowsStateTriggers for the final SDK. Go grab the source code today!

During the beta period I’ve received several great fixes and additions from the community. Thank you all who contributed!

The Nuget package is available here: https://www.nuget.org/packages/WindowsStateTriggers

Get full source here: https://github.com/dotMorten/WindowsStateTriggers

 

See the WIKI or Test App for usage some usage examples.

Create a Universal 3D App in a matter of minutes

We just released version 10.2.6 of 'ArcGIS Runtime for .NET SDK', which now supports 3D and KML files on both Windows Store 8.1, Windows Phone 8.1 and WPF. This means you can now quickly build 3D applications that supports all these platforms. We also released the package on NuGet for your convenience.

As a demonstration how quick it is to create a Windows Phone and Windows Store 3D app, here's a little video creating a universal 3D app from scratch in a couple of minutes:

Displaying a backbutton on your app title bar

Disclaimer: This article is written based on Windows 10 Tech Preview – Build 10122. Things might change completely in the future.

Some of the Windows 10 apps have a back button at the top of the app bar. Here’s an example in the Settings Control Panel:

image

We can add this to our own apps but using the SystemNavigationManager’s AppViewBackButtonVisibility.

Here’s how that will look like:

SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

When you run this code you’ll now also see the exact same back button in your Windows UWP Desktop app! No need to waste precious screen real-estate when there’s room on the top bar.

Of course for Windows Phone this isn’t really needed (although nothing seems to happen if you call this API), call it anyway, just in case you're running on a device that can show the backbutton - it seems like it just doesn't show on devices with hardware:


   //Show UI back button - do it on each page navigation
   if (Frame.CanGoBack)
      SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
   else
      SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;


   //Hook up back buttons - Do this just once - ie on app launched
   SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>
   {
       if (Frame.CanGoBack)
           Frame.GoBack();
   };
   if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
   {
       //Also use hardware back button
       Windows.Phone.UI.Input.HardwareButtons.BackPressed += (s, e) =>
       {
           if (Frame.CanGoBack)
           {
               e.Handled = true;
               Frame.GoBack();
           }
       };
   }

Now you get back button support in both desktop and phone apps when you can navigate back!

Unfortunately the BackRequested and BackPressed event arguments are different, so you can’t reuse the same event handler for both. That’s quite a shame – I hope Microsoft will be cleaning that up soon.

Creating DeviceFamily specific layouts in a Universal App

Disclaimer: This article is written based on Windows 10 Tech Preview – Build 10041. Things might change completely in the future.

In an earlier post, I showed how to use a StateTrigger to adapt parts of your UI to a specific device family (Device families are: Windows Desktop, Windows Mobile, XBox, IoT etc).

However if you want to do major differences in your UI, that’s probably not the most efficient way. Windows 10 comes with a nice trick to use completely different XAML files based on the device family you’re running on.

Let’s first create a new blank UAP project, and add the following XAML to the main <Grid> on MainPage.xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <TextBlock Text="Hello Windows Desktop"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                />        
 
</Grid>

 

When you run this on Desktop,you not surprisingly get this:

image

And also not surprising you get this on Windows Phone:

image

Now what we want to do is override the MainPage.xaml for Windows Phone and display a more correct message.

First create a new folder called DeviceFamily-[family] where [family] is ‘Mobile’:

image

Right-click this folder and choose “Add new item”

image

Pick “Xaml View” and change the name to “MainPage.xaml” This page is similar to a blank page; but is for overriding specific XAML pages – ie it doesn’t include the code behind, which you already have.

Now add the new TextBlock to this page with a more device family specific message:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <TextBlock Text="Hello Windows Phone" 
                HorizontalAlignment="Center"
                VerticalAlignment="Center" />
        
</Grid>

Because this XAML file ii in the DeviceFamily-Mobile, when running on Windows mobile, this XAML will be used instead of the default MainPage.xaml defined in the root of the project

image

So this method enables you to completely override the UI and adapt for the device family and maintain the same code-behind.

Using Custom Visual State Triggers

Disclaimer: This article is written based on Windows 10 Tech Preview – Build 10041. Things might change completely in the future.

The Windows 10 Preview SDK was finally released, and we all finally get a peek at what the new Universal App Projects (UAP) are all about. It’s one binary that will run everywhere. This means that it’s also one XAML to run both on Windows and Windows Phone. But because the user experience is usually quite different you might want a different UI for it. So a new functionality was added to Visual State that allows you to easily change the layout based on the width of your window. So the idea is that the layout adapts not based on device, but by screen real-estate. Here’s what that could look like:

<Grid >
  <VisualStateManager.VisualStateGroups>
    <VisualStateGroup >
      <VisualState x:Name="narrow">
        <VisualState.StateTriggers>
          <AdaptiveTrigger MinWindowWidth="0" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
          <Setter Target="status.Text" Value="Narrow view" />
        </VisualState.Setters>
      </VisualState>
      <VisualState x:Name="wide">
        <VisualState.StateTriggers>
          <AdaptiveTrigger MinWindowWidth="600" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
          <Setter Target="status.Text" Value="Wide view" />
        </VisualState.Setters>
      </VisualState>
    </VisualStateGroup>
  </VisualStateManager.VisualStateGroups>
  
  <TextBlock x:Name="status" FontSize="40"
  HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
WideNarrowState

So the basic idea is that by using the AdaptiveTrigger, when the window gets small enough, switch to the phone/narrow UI. So on a phone it’ll probably always be this UI used. Pretty neat, and allows for a similar experience across devices, but adapt for bigger screens.

When taking a closer look at the StateTriggers property, it takes a collection of ‘StateTrigger’, which is an abstract class that AdaptiveTrigger inherits from. So it stands to reason that perhaps we can create our own state triggers?

Supposed basing your UI on the width isn’t good enough, and you want to base it on the platform you’re on (Windows vs Windows Phone), we can create a new state trigger for this purpose. All we have to do is call the base method SetTriggerValue(bool) whether the conditions of the state is enabled or not. So here’s what a class like that would look like:

public class DeviceTypeAdaptiveTrigger : StateTriggerBase
{
    public DeviceType PlatformType
    {
        get { return (DeviceTypeAdaptiveTrigger.DeviceType)GetValue(DeviceTypeProperty); }
        set { SetValue(DeviceTypeProperty, value); }
    }
 
    public static readonly DependencyProperty DeviceTypeProperty =
        DependencyProperty.Register("DeviceType", typeof(DeviceType), typeof(DeviceTypeAdaptiveTrigger),
        new PropertyMetadata(DeviceType.Unknown, OnDeviceTypePropertyChanged));
 
    private static void OnDeviceTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var obj = (DeviceTypeAdaptiveTrigger)d;
        var val = (DeviceType)e.NewValue;
        var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;
        if (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile")
            obj.SetTriggerValue(val == DeviceType.Mobile);
        if (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Desktop")
            obj.SetTriggerValue(val == DeviceType.Desktop);
    }
 
    public enum DeviceType
    {
        Unknown = 0, Desktop = 1, Mobile = 2,
    }
}

And we can use this in XAML this way:

<VisualStateGroup>
    <VisualState x:Name="windows">
        <VisualState.StateTriggers>
            <triggers:DeviceTypeAdaptiveTrigger DeviceType="Desktop" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="greeting.Text" Value="Hello Windows!" />
        </VisualState.Setters>
    </VisualState>
    <VisualState x:Name="phone">
        <VisualState.StateTriggers>
            <triggers:DeviceTypeAdaptiveTrigger DeviceType="Mobile" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="greeting.Text" Value="Hello Phone!" />
        </VisualState.Setters>
    </VisualState>
</VisualStateGroup>

image

I’ve created a few more triggers and put them on Github. I won’t go into the code here, but you can grab the source up there. But instead here’s how we can use some of these:

OrientationStateTrigger: Adapt the UI based on the screen orientation: Portrait or Landscape

<VisualStateGroup>
    <VisualState x:Name="landscape">
        <VisualState.StateTriggers>
            <triggers:OrientationStateTrigger Orientation="Landscape" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="orientationText.Text" Value="Landscape!" />
        </VisualState.Setters>
    </VisualState>
    <VisualState x:Name="portrait">
        <VisualState.StateTriggers>
            <triggers:OrientationStateTrigger Orientation="Portrait" />
        </VisualState.StateTriggers>
        <VisualState.Setters>
            <Setter Target="orientationText.Text" Value="Portrait!" />
        </VisualState.Setters>
    </VisualState>
</VisualStateGroup>

IsTypePresentStateTrigger: Enabled/disable UI based on whether a certain API is available. For instance if a hardware back button is present (usually Windows Phone), we can hide the back button from the UI, and free up some screen space.

<VisualState x:Name="backButton">
    <VisualState.StateTriggers>
        <triggers:IsTypePresentStateTrigger TypeName="Windows.Phone.UI.Input.HardwareButtons" />
    </VisualState.StateTriggers>
    <VisualState.Setters>
        <Setter Target="BackButton.Visibility" Value="Collapsed" />
    </VisualState.Setters>
</VisualState>

Now the next question is: Does these values support binding? If they do, these triggers could be the new equivalent of WPF’s DataTriggers. So let’s create a simple data trigger that turns something on, based on a boolean. We can implement a simple IsTrueStateTrigger / IsFalseStateTrigger and just call the base method if the value we bound is true or not.

<VisualState>
    <VisualState.StateTriggers>
        <triggers:IsTrueStateTrigger Value="{Binding MyBoolean}" />
    </VisualState.StateTriggers>
    <VisualState.Setters>
        <Setter Target="box.Visibility" Value="Collapsed" />
    </VisualState.Setters>
</VisualState>

Of course I could use a value converter for this as well, but this has a lot greater flexibility – a converter would have to be written to convert to Visible/Collapsed state, whereas this trigger can set any property to any value type.

Got any more ideas for useful generic state triggers? Fork and make a pull request!

https://github.com/dotMorten/WindowsStateTriggers

Big props goes to Scott Lovegrove for directing my attention to the possibility of custom state triggers

Fixing Visual Studio’s auto generated code

I usually have a zero-tolerance when it comes to build warnings. While granted often the warnings are benign, having a lot will very often hide the important ones. Sometimes I even set the option “treat warnings as errors” to help me enforce this. When you’re building a library, you should also add XML doc comments to your classes and members, so you get full intellisense support in the projects you’re using it from. Just remember to check off the following check box:

image

This also have the benefit of giving you warnings for missing doc comments on public members, so you remember to write proper doc. However if you’re building for Windows Store or Phone, there’s a good chance you’ll see these four warnings now:

image

These are coming from code auto-generated by the compiler which exposes a set of public classes. You can even see these in intellisense:

image

This is a major issue in my mind. First of all it introduces warnings in code you didn’t write, and it pollutes your class library with methods that are not meant to be used. Here’s what this auto-generated class looks like:

image

The fix seems simple: Just go in and add the doc comments, and problem is solved, right? Not really. The problem is any changes you make to this file is overwritten every time you build. So we need to tweak the file right after it’s being generated, but right before it’s being compiled, but who’s that fast?

Enter: The Build Task

We can use a build task to do exactly that, and tell Visual Studio to let us know that its about to compile the code and fix it ourselves.

First create a new empty Windows Class Library, and add the following two references:

image

Next add the following class and compile:

XamlTypeInfoBuildTask.cs

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;

namespace XamlBuildTasks
{
    public class XamlTypeInfoBuildTask : Task
    {
        private const string XamlTypeInfoFileName = "XamlTypeInfo.g.cs";

        [Required]
        public string IntermediateOutputPath { get; set; }       
       
        public override bool Execute()
        {
            string filename = IntermediateOutputPath + XamlTypeInfoFileName;
            if (!System.IO.File.Exists(filename))
                return false;
            string code = System.IO.File.ReadAllText(filename);

            if (code.StartsWith("#pragma warning disable 1591")) //Already modified
                return true;
            int idx = code.IndexOf("[System.CodeDom.Compiler.GeneratedCodeAttribute");
            if (idx < 0)
                return false;
            string insert = "[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n";
            code = "#pragma warning disable 1591\n" + code.Substring(0, idx) + insert + code.Substring(idx) +
                "#pragma warning restore 1591\n";
            System.IO.File.WriteAllText(filename, code);
            return true;
        }
    }
}

What does this class do? Simple: It has one property: The folder where the intermediate files including XamlTypeInfo.g.cs is. It then opens the file to be modified, and first injects “#pragma warning disable 1591” at the header which disables doc warnings, and re-enables it again at the bottom. At the same time we hide the class from intellisense, by setting the EditorBrowsable attribute on the class. This doesn’t really remove the class from the assembly – it just tells Visual Studio to skip showing this for intellisense.

To use this build-task, we need to add a little bit to the project file that causes this issue. We’ll first create a .targets file with the parameters for buildtask. Place this next to the compiled DLL (and use the name of the dll where highlighted):

XamlTypeInfoBuildTask.targets

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="XamlTypeInfoBuildTask"
            AssemblyFile="$(MSBuildThisFileDirectory)XamlBuildTask.dll" />
  <Target Name="MyBuildTask" AfterTargets="MarkupCompilePass2" BeforeTargets="CoreCompile">
    <XamlTypeInfoBuildTask IntermediateOutputPath="$(IntermediateOutputPath)" />
  </Target>
</Project>

This tells the project to run this before the compilation after the markup has been processed. It also sets the IntermediateOutputPath property on our build task, so the build task can find the file.

Now the last step is to reference this .targets file from the csproj file. Open the csproj file up in notepad, and scroll down to the <Import…/> tags, and add the following (remember to modify the highlighted paths to where the targets file is:

  <Import Project="..\..\..\build\XamlTypeInfoBuildTask.targets" Condition="Exists('..\..\..\build\XamlTypeInfoBuildTask.targets')" />

Now when we build, we get a nice pretty build with no warnings:

image

And here’s all the auto-generated classes, gone from intellisense:

image

Making all this simpler

Naturally this is a bit of a pain having to set up over and over again. So unless you ever have to do a similar build task, you can forget everything you just read (sorry Smile), and just use the Nuget package I created that’ll do all this for you.

Simply add a reference to this nuget package, and the build task dll is downloaded and the .targets file auto-referenced.

And if you want the source code? It’s all available here on Github: https://github.com/dotMorten/XamlTypeInfoBuildTask

Enjoy!