WPF DependencyProperty不接受short的默认值

4

我试图在我的代码中使用这个依赖属性,但它给了我一个错误,说默认值类型与属性 'MyProperty' 的类型不匹配。 但是 short 应该接受 0 作为默认值。

如果我尝试将其设置为 null 作为默认值,则可以工作,即使它是非空类型。 这是怎么发生的..

public short MyProperty
{
   get { return (short)GetValue(MyPropertyProperty); }
   set { SetValue(MyPropertyProperty, value); }
}

将一个DependencyProperty作为MyProperty的后备存储。这样可以实现动画、样式、绑定等功能...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register(
        "MyProperty",
        typeof(short),
        typeof(Window2),
        new UIPropertyMetadata(0)
    );
2个回答

13
问题在于C#编译器将文字值解释为整数。你可以告诉它将其解析为长整型或无符号长整型(40L是长整型,40UL是无符号长整型),但是没有简单的方法声明短整型。
只需进行强制转换即可解决问题:
public short MyProperty
{
    get { return (short)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

public static readonly DependencyProperty MyPropertyProperty = 
   DependencyProperty.Register(
      "MyProperty", 
      typeof(short),
      typeof(Window2),
      new UIPropertyMetadata((short)0)
   );

0
public short MyProperty
{
    get { return (short)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}


// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(short), typeof(Window2), new UIPropertyMetadata((short)0));
     }

这似乎有效...看起来0将被解释为int..但是为什么..?


2
UIPropertyMetadata构造函数获取对象参数,因此没有转换。C#规范指出,整数字面量用于编写int、uint、long和ulong类型的值。当您不使用强制转换写入0时,将得到一个int。 - majocha
2
不要回答自己的问题。更新它。 - user1228
如果我更新了我的问题,那么它就不再是一个问题了,那么其他遇到相同问题的人将如何受益呢? - biju
2
您可以回答自己的问题,详见常见问题解答。 - Wallstreet Programmer
@Will 好的,我没有回答我的问题。我发布了一个解决方法,并且我提出问题是为了保持讨论的开放性。正如你所看到的,我得到了我想要的答案。如果你无法回答它,为什么不直接离开...何必费心呢? - biju
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接