2

在他的一篇博文中,Laurent Bugnion 演示了以下代码片段作为检测 wpf 设计时间模式的一种方法

private static bool? _isInDesignMode;


/// <summary>
/// Gets a value indicating whether the control is in design mode (running in Blend
/// or Visual Studio).
/// </summary>
public static bool IsInDesignModeStatic
{
    get
    {
        if (!_isInDesignMode.HasValue)
        {
#if SILVERLIGHT
            _isInDesignMode = DesignerProperties.IsInDesignTool;
#else
            var prop = DesignerProperties.IsInDesignModeProperty;
            _isInDesignMode
                = (bool)DependencyPropertyDescriptor
                .FromProperty(prop, typeof(FrameworkElement))
                .Metadata.DefaultValue;
#endif
        }

        return _isInDesignMode.Value;
    }
}

当我碰巧在 VB 中工作时,我开始使用 Telerik 的在线代码转换器进行翻译,结果如下:

Private Shared _isInDesignMode As System.Nullable(Of Boolean)

''' <summary>
''' Gets a value indicating whether the control is in design mode (running in Blend
''' or Visual Studio).
''' </summary>
Public Shared ReadOnly Property IsInDesignModeStatic() As Boolean
    Get
        If Not _isInDesignMode.HasValue Then
            #If SILVERLIGHT Then
            _isInDesignMode = DesignerProperties.IsInDesignTool
            #Else
            Dim prop = DesignerProperties.IsInDesignModeProperty
                #End If
            _isInDesignMode = CBool(DependencyPropertyDescriptor.FromProperty(prop, GetType(FrameworkElement)).Metadata.DefaultValue)
        End If

        Return _isInDesignMode.Value
    End Get
End Property

但是,如果一个人启用了 Option Strict On(默认情况下我这样做,这将无法编译,指出 system.windows.DependencyProperty 和 system.ComponentModel.DependencyProperty 之间存在差异。

代码转换器抛出的大多数错误我通常可以最终修复,但是这个(可能是因为整个 wpf 对我来说很新)给我带来了问题。

任何人都可以解释错误的根本原因(以便我可以积极理解它)并可能提供更正的 vb 转换。

谢谢

4

1 回答 1

1

那么以下似乎工作:

Private Shared _isInDesignMode As System.Nullable(Of Boolean)

Public Shared ReadOnly Property IsInDesignMode() As Boolean
Get
    Dim prop As DependencyProperty   
    If Not _isInDesignMode.HasValue Then
        #If SILVERLIGHT Then
        _isInDesignMode = DesignerProperties.IsInDesignTool
        #Else
          prop  = DesignerProperties.IsInDesignModeProperty
            #End If
        _isInDesignMode = CBool(DependencyPropertyDescriptor.FromProperty(prop, GetType(FrameworkElement)).Metadata.DefaultValue)
    End If

    Return _isInDesignMode.Value
End Get
End Property

有两件事值得注意。

  1. 可能在 Laurent 的原始博客中有一个错字,因为私有和公共静态声明之间存在不匹配(尽管智能感知似乎没有对此提出异议!)。也许那是 C# 的事情,我对 C# 的了解还不够,无法对此发表评论。
  2. Option Strict On 要求使用 AS 语句声明变量。prop 被声明为 system.windows.DependencyProperty,但被分配为 system.cComponentModel.DependencyProperty。编译器似乎并没有像这样反对它。我不知道为什么。

如果你们中的任何人对 C# 和 VB 之间的差异有更清楚的了解,可以对此有所了解,我很高兴知道为什么会这样,而不是仅仅接受它似乎有效。

于 2014-10-10T13:29:37.780 回答