如何从XAML绑定到解决方案配置?

时间:2012-02-07 15:04:23

标签: c# wpf xaml

当我使用Release配置构建应用程序时,我想将属性设置为true,否则我想将其设置为false。我有以下内容:

<Window Topmost="{Binding IsReleaseBuild}">

通常我会使用预处理程序指令#if#endif来检查DEBUG常量,但这在XAML中是不可能的。

处理此问题的最佳方式是什么?

Most likely我可以创建一个可以在数据上下文中绑定的值。但是,我更愿意创建一个可重用的解决方案。

我也可以在代码隐藏文件中使用预处理程序指令,但我想知道是否有更清晰的解决方案。

2 个答案:

答案 0 :(得分:1)

你可以简单地做这样的事情;基于您发布的链接中的解决方案。

public bool IsReleaseBuild
{
    get { return MyStaticClass.IsAssemblyDebugBuild(Assembly.GetExecutingAssembly()); }
}

如果您使用的是MVVM,则只需将Property放入BaseClass并允许所有View/ViewModels使用。

它可能看起来像这样。

public class BaseViewModel : ObservableObject
{
    public Boolean IsReleaseBuild
    {
        get
        {
           ...
        }
    }
}

我做了类似的事情,以确定我的应用程序当前是否在Visual Studio Design Mode

public class BaseViewModel : ObservableObject
{
    private static Nullable<Boolean> _isInDesignMode;

    public Boolean IsInDesignMode
    {
        get
        {
            if (!_isInDesignMode.HasValue)
            {
                DependencyProperty property = DesignerProperties.IsInDesignModeProperty;

                _isInDesignMode
                    = (bool)DependencyPropertyDescriptor
                                    .FromProperty(property, typeof(FrameworkElement))
                                    .Metadata.DefaultValue;
            }

            return _isInDesignMode.Value;
        }
    }
}

答案 1 :(得分:1)

附属物怎么样?

public sealed class Solution
{
    public static readonly DependencyProperty IsReleaseBuildProperty =
        DependencyProperty.RegisterAttached(
        "IsReleaseBuild",
        typeof(bool),
        typeof(Solution),
        new FrameworkPropertyMetadata(
#if DEBUG
            false
#else
            true
#endif
           ));

    public static bool GetIsReleaseBuild(DependencyObject source)
    {
        return (bool)source.GetValue(IsReleaseBuildProperty);
    }
}

在你的XAML中:

<Window Topmost="{Binding RelativeSource={RelativeSource Self} Path=util:Solution.IsReleaseBuild}" />