为了测试目的,我试图在调试和发布配置中显示WPF控件中的不同视图元素。我用这篇文章作为指南:Does XAML have a conditional compiler directive for debug mode? (SO)
为了测试它,我用一个名为VS2013的WPF应用程序项目创建了一个TestingAlternateContent解决方案。在我的AssemblyInfo.cs中,我添加了以下代码:
#if DEBUG
[assembly: XmlnsDefinition("debug-mode", "TestingAlternateContent")]
#endif在我的MainWindow.xaml中,我创建了一个简单的代码示例来测试这种行为,如下所示:
<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>在测试时,我总是看到窗口上有“这里的发布模式!”消息,不管我使用的是哪种配置(调试,关联)。我已经检查了AssemblyInfo #if调试是否正常工作,当我在调试/发行版配置之间进行更改时,会相应地进行更改。我在and 2008/and 2013下用.NET Framework3.5/4.5版本测试了相同的代码,但没有一种有效。我遗漏了什么?有人知道这里出了什么问题,或者可以将工作代码作为参考吗?
发布于 2016-03-22 10:10:43
问题是在解析XAML之后解析了XmlnsDefinitionAttribute,所以它不适用于同一个程序集。
但是,您可以在解决方案中的任何其他(引用)项目中使用该XmlnsDefinition,它将工作。
这就是:
TestingAlternateContent) MainWindow.Xaml
- Contains the `XmlsDefinitionAttribute` with the namespace of `TestingAlternateContent`:#if调试程序集:XmlnsDefinition(“调试-模式”,"TestingAlternateContent") #endif
我刚刚测试了它,它工作得很好,没有修改程序集属性声明或Xaml,只需将它添加到不同的项目中。
发布于 2016-03-22 09:53:57
我不认为XAML设计器有一个很好的编译器指令,不幸的是,我使用了一个附加属性来改变可见性,这是非常好的,因为它也显示在设计器中。
<Window x:Class="DebugTest.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:local="clr-namespace:DebugTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button local:MainWindow.IsDebugOnly="True" Width="100" Height="100" Content="Debug only"/>
</Grid>
此处附加的属性位于MainWindow类中,但它可能在任何您想要的实用程序类中。
using System.Windows;
namespace DebugTest
{
public partial class MainWindow : Window
{
public static bool GetIsDebugOnly(DependencyObject obj)
{
return (bool)obj.GetValue(IsDebugOnlyProperty);
}
public static void SetIsDebugOnly(DependencyObject obj, bool value)
{
obj.SetValue(IsDebugOnlyProperty, value);
}
public static readonly DependencyProperty IsDebugOnlyProperty = DependencyProperty.RegisterAttached("IsDebugOnly", typeof(bool), typeof(MainWindow), new PropertyMetadata(false, new PropertyChangedCallback((s, e) =>
{
UIElement sender = s as UIElement;
if (sender != null && e.NewValue != null)
{
bool value = (bool)e.NewValue;
if (value)
{
#if DEBUG
bool isDebugMode = true;
#else
bool isDebugMode = false;
#endif
sender.Visibility = isDebugMode ? Visibility.Visible : Visibility.Collapsed;
}
}
})));
public MainWindow()
{
InitializeComponent();
}
}
}https://stackoverflow.com/questions/36150073
复制相似问题