我试图在我的代码中使用tis depencency属性,但它给了我错误,说默认值类型与属性'MyProperty'的类型不匹配。 但是short应该接受0作为默认值。
如果我尝试将其作为默认值赋予它,则它可以工作,即使它是非nullabel类型。 怎么会发生这种情况..
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)
);
答案 0 :(得分:13)
问题是C#编译器将文字值解释为整数。您可以告诉它将它们解析为long或ulongs(40L是长的,40UL是ulong),但是没有简单的方法来声明短路。
简单地投射文字将起作用:
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)
);
答案 1 :(得分: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 ..但为什么..?