简体   繁体   English

XAML中的预处理器条件编译

[英]Preprocessor conditional compilation in XAML

I've got some code written in C# WPF, and I've got some code for debugging, which I currently compile on or off for debug or release mode. 我有一些用C#WPF编写的代码,我有一些调试代码,我目前正在编译或关闭调试或发布模式。 How can I enable or disable UI controls which are currently written in my XAML based on C# preprocessor definitions? 如何启用或禁用当前基于C#预处理器定义在我的XAML中编写的UI控件?

You can add some code in the constructor that enables/disables the elements: 您可以在构造函数中添加一些启用/禁用元素的代码:

public MainWindow()
{
    InitializeComponent();

#if DEBUG
    button1.IsEnabled = false;
#endif
}

There are no preprocessor-style directives for XAML. XAML没有预处理器样式的指令。 However, you could include and exclude XAML files based on the build configuration, providing you with some control. 但是,您可以根据构建配置包含和排除XAML文件,从而为您提供一些控制。 This could provide you with a way of including variations of a file depending on the chosen build configuration. 这可以为您提供一种根据所选构建配置包含文件变体的方法。 Of course, the downside is that you would have to maintain multiple versions of a file. 当然,缺点是您必须维护文件的多个版本。 This could be mitigated through the use of T4 templates so that the different files are auto-generated according to the selected configuration. 这可以通过使用T4模板来减轻,以便根据所选配置自动生成不同的文件。

There are two ways to do this. 有两种方法可以做到这一点。 One is using the Preprocessor directives that can mask complete sections of code running it only in a particular build. 一种是使用预处理程序指令,它可以屏蔽仅在特定构建中运行它的代码的完整部分。 Or you can use the the Conditional Attribute to easily block out a complete method. 或者,您可以使用条件属性轻松阻止完整方法。 http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=420 http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=420
Here's a description of the difference between the two : http://www.thinkfarahead.com/2007/09/if-debug-vs-conditional.html . 以下是两者之间差异的描述: http//www.thinkfarahead.com/2007/09/if-debug-vs-conditional.html You can reference the controls in your code by providing an x:Name attribute in xaml and putting the code to disable the controls in conditional section of your code. 您可以通过在xaml中提供x:Name属性并将代码设置为禁用代码的条件部分中的控件来引用代码中的控件。

Updated: to be clearer mentioned x:Name attribute. 更新:更清楚地提到x:Name属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM