wpf DependencyProperty 不接受短默认值

标签 wpf dependency-properties default-value

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

如果我尝试给它一个 null 作为默认值,它可以工作,即使它是非 nullabel 类型。
怎么会这样。。

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

使用 DependencyProperty 作为 MyProperty 的后备存储。这可以实现动画、样式、绑定(bind)等...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register(
        "MyProperty",
        typeof(short),
        typeof(Window2),
        new UIPropertyMetadata(0)
    );

最佳答案

问题在于 C# 编译器将文字值解释为整数。您可以让它将它们解析为 long 或 ulong(40L 是 long,40UL 是 ulong),但没有简单的方法来声明 short。

简单地转换文字就可以了:

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)
   );

关于wpf DependencyProperty 不接受短默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652953/

相关文章:

c# - 在 VS2012 中读取任何 WPF 项目的资源文件时出错

WPF 绑定(bind)到可视树中某处的附加属性

wpf - 如何在 WPF TextBox 上为无效的依赖属性显示红色边框?

wpf - MVVM 本地化 - View 中的本地化资源与 ViewModel 中的资源?

c# - 从 Windows 10 虚拟键盘输入 WPF 文本框的快乐表情符号未在文本框的 PreviewTextInput 事件中捕获

c# - DependencyProperties 未按预期在 UserControl 中触发回调

hibernate - Grails 1.3.9应用程序中的EHCache默认值

c++ - 如何优雅地返回默认初始化的对象?

php - MySQL 默认 date() + 14 天,对于一个列?

c# - Prism:如何使用 Unity Bootstrapper 在 Shell 区域中加载默认 View