Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF AlternateContent not working

Tags:

c#

.net

wpf

xaml

I am trying to show different view elements in a WPF control in debug and release configurations for testing purposes. I have used this post as a guide: Does XAML have a conditional compiler directive for debug mode? (SO)

In order to test it, I have created a VS2013 solution with a single WPF app project, called TestingAlternateContent. Inside my AssemblyInfo.cs I have added the following code:

#if DEBUG
    [assembly: XmlnsDefinition("debug-mode", "TestingAlternateContent")]
#endif

In my MainWindow.xaml I have created a simple code sample to test this behaviour as follows:

<Window x:Class="TestingAlternateContent.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:debug="debug-mode"        
        mc:Ignorable="mc debug" 

        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <mc:AlternateContent>
            <mc:Choice Requires="debug">
                <TextBlock Text="Debug mode!!" />
            </mc:Choice>
            <mc:Fallback>
                <TextBlock Text="Release mode here!" />
            </mc:Fallback>
        </mc:AlternateContent>
    </Grid>
</Window>

While testing this, I always see the window with the "Release mode here!" message, regardless which configuration (Debug, Relase) I am using. I have checked that the AssemblyInfo #if DEBUG is working propperly, changing accordingly when I change between Debug/Release configurations. I have tested the same code under VS2008/VS2013 with .NET Framework 3.5/4.5 versions, and none have worked. What am I missing? Anyone knows what is wrong here or can post a working code as reference?

like image 334
estradjs Avatar asked Mar 22 '16 09:03

estradjs


1 Answers

The problem is that the XmlnsDefinitionAttribute is parsed after the XAML is parsed, so it doesn't work for the same assembly.

You can however, make that XmlnsDefinition in any other (referenced) project in your solution, and it'll work

That is:

  • ProjectA (Namespace: TestingAlternateContent)
    • Contains your MainWindow.Xaml
    • References ProjectB
  • ProjectB

    • Contains the XmlsDefinitionAttribute with the namespace of TestingAlternateContent:

      #if DEBUG
      [assembly: XmlnsDefinition("debug-mode", "TestingAlternateContent")]
      #endif
      

I just tested it, and it works fine, no modifications to either the assembly attribute declaration or to the Xaml, just adding it on a different project

like image 68
Jcl Avatar answered Sep 19 '22 22:09

Jcl