XAML是否有针对调试模式的条件编译器指令?

Ehs*_*adi 65 c# wpf xaml

对于XAML中的样式我需要这样的东西:

<Application.Resources>

#if DEBUG
    <Style TargetType="{x:Type ToolTip}">
        <Setter Property="FontFamily" Value="Arial"/>
        <Setter Property="FlowDirection" Value="LeftToRight"/>
    </Style>
#else
    <Style TargetType="{x:Type ToolTip}">
        <Setter Property="FontFamily" Value="Tahoma"/>
        <Setter Property="FlowDirection" Value="RightToLeft"/>
    </Style>
#endif

</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

bj0*_*bj0 111

我最近不得不这样做,当我无法轻易找到任何明确的例子时,我感到很惊讶.我所做的是将以下内容添加到AssemblyInfo.cs:

#if DEBUG
[assembly: XmlnsDefinition( "debug-mode", "Namespace" )]
#endif
Run Code Online (Sandbox Code Playgroud)

然后,使用markup-compatability命名空间的AlternateContent标记根据该命名空间定义的前缀选择您的内容:

<Window x:Class="Namespace.Class"
        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:d="debug-mode"

        Width="400" Height="400">

        ...

        <mc:AlternateContent>
            <mc:Choice Requires="d">
                <Style TargetType="{x:Type ToolTip}">
                    <Setter Property="FontFamily" Value="Arial"/>
                    <Setter Property="FlowDirection" Value="LeftToRight"/>
                </Style>
            </mc:Choice>
            <mc:Fallback>
                <Style TargetType="{x:Type ToolTip}">
                    <Setter Property="FontFamily" Value="Tahoma"/>
                    <Setter Property="FlowDirection" Value="RightToLeft"/>
                </Style>
            </mc:Fallback>
        </mc:AlternateContent>

        ...
</Window>
Run Code Online (Sandbox Code Playgroud)

现在,当定义DEBUG时,还将定义"debug-mode",并且将存在"d"命名空间.这使得AlternateContent标记选择第一个代码块.如果未定义DEBUG,则将使用Fallback代码块.

这个示例代码没有经过测试,但它与我当前项目中有条件地显示一些调试按钮的内容基本相同.

我确实看到一篇博客文章,其中包含一些依赖于"Ignorable"标签的示例代码,但这种方法似乎不太清晰且易于使用.

  • VS错误窗格不喜欢这个,虽然一切都按预期工作:[link](http://stackoverflow.com/questions/24459716/alternatecontent-tags-causing-issues-with-ide-but-not-compiler) (5认同)
  • 请注意,您可能需要标记"mc"对自身可忽略,即mc:Ignorable ="d mc" (4认同)
  • 如果您在 AlternateContent 之间使用向 IComponentConnector.Connect 方法添加代码的功能(像 OnClick 这样的事件处理程序就是这样做的),则 connectionId 会完全搞砸,并且 InitializeComponent 将在运行时失败或执行意外的操作(混淆事件处理程序)。 (2认同)
  • 知道为什么在 Xamarin 中我收到此错误“在 xmlns http://schemas.openxmlformats.org/markup-compatibility/2006 中找不到类型 mc:Choice”? (2认同)