为什么“propdp”代码片段没有在声明依赖属性的位置提供正确的类名称?

jos*_*lmt 1 c# visual-studio code-snippets visual-studio-2015

当您使用propdp代码片段创建依赖项属性时,它不会为您建议创建依赖项属性的类的正确名称,您必须手动键入它,如下例所示:

namespace YourApp.Controls
{
    public sealed class YourButton : Control
    {
        public YourButton()
        {
            this.DefaultStyleKey = typeof(YourButton);
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(ownerclass), new PropertyMetadata(0));
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想作为默认值Ownerclass,在这种情况下我想要YourButton

如何修改代码片段以提出正确的名称?

jos*_*lmt 5

分析ctor代码片段的源代码,很容易知道问题所在:只需添加下一行:

<Function>ClassName()</Function>
Run Code Online (Sandbox Code Playgroud)

在字面所有者类的定义中。

  • 打开文件 C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC#\Snippets\1033\NetFX30\propdp.snippet。
  • 在所有者类的定义中添加该行。
  • 保存文件。
  • 重新启动 Visual Studio。

该文件必须是这样的:

...
<Literal>
    <ID>ownerclass</ID>
    <ToolTip>The owning class of this Property.  Typically the class that it is declared in.</ToolTip>
    <Function>ClassName()</Function>
    <Default>ownerclass</Default>
</Literal>
...
Run Code Online (Sandbox Code Playgroud)

然后你就会默认得到你想要的:

namespace YourApp.Controls
{
    public sealed class YourButton : Control
    {
        public YourButton()
        {
            this.DefaultStyleKey = typeof(YourButton);
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(YourButton), new PropertyMetadata(0));
    }
}
Run Code Online (Sandbox Code Playgroud)

使用为什么“propdp”代码片段不使用 nameof 运算符作为注册属性的名称?中建议的修改 使用nameof运算符来获得它。