我试图在我的代码中使用 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/