XAML条件编译

有没有一种简单的方法可以在我的xaml文件中使用我用于c#代码的相同条件编译符号?

在XAML中有一些对条件编译的支持。 但它与C#代码不同。 诀窍是使用AlternateContentRequires来标记Ignorable 。 通过执行此操作,您实际上可以根据条件使部分xaml不可用,并打开或关闭。

我尝试了其他提到的解决方案,它编译并运行,即使Visual Studio会给你带来大量错误,对我来说,解决方案似乎在UI线程上花了很多时间,我不喜欢这两种情况。

我实现的最佳解决方案是将所有条件逻辑放在控件后面的代码中。 由于您没有提及您的意图,这可能就是您所寻找的。

我希望在我的应用程序中有一个条件编译符号影响颜色,但你也可以设想用于其他不同样式甚至模板的相同解决方案,或者这可以与通常的if-else逻辑而不是编译符号一起使用。

   #068C00 #5EBD50 DarkGreen     #EF0000 #e62621 #EF0000    

可以通过在应用程序中放置MainStyle.xaml.cs来手动创建代码隐藏,并像这样使用它:

 using System.Windows; namespace MyApp.Style { partial class MainStyle : ResourceDictionary { public MainStyle() { InitializeComponent(); #if VERSION2 this["MainColor"] = this["OtherRedColor"]; this["LighterMainColor"] = this["LighterRedColor"]; this["DarkerMainColor"] = this["DarkerRedColor"]; #elif VERSION1 this["MainColor"] = this["AbMainColor"]; this["LighterMainColor"] = this["AbLighterMainColor"]; this["DarkerMainColor"] = this["AbDarkerMainColor"]; #endif } } } 

需要注意的是,如果只引用我的XAML代码中的未设置值,并且这也适用于StaticResource ,尽管构造函数只被调用一次。 我想覆盖/使用更多的资源字典方法也可以,但这已经解决了我的问题,所以我没有尝试。