【发布时间】:2013-05-06 12:09:16
【问题描述】:
将 Integer 分配给 double 是非常合法的。
如果可以的话
double d = 3;
d 被分配3.0
但是为什么这在附加属性中失败了?
场景
我创建了一个附加属性
public static readonly DependencyProperty ActualWidthBeforeHidingProperty =
DependencyProperty.RegisterAttached("ActualWidthBeforeHiding",
typeof(double), typeof(MainWindow), new FrameworkPropertyMetadata(0));
public static double GetActualWidthBeforeHiding(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return Convert.ToDouble(element.GetValue(ActualWidthBeforeHidingProperty));
}
public static void SetActualWidthBeforeHiding(DependencyObject element, double value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ActualWidthBeforeHidingProperty, value);
}
我编译了代码。没有编译时错误。
但是当我尝试运行应用程序时,它给出了错误
上面代码中我不小心把new FrameworkPropertyMetadata(0)赋值为0,代码运行成功。
但我的印象是,您可以将精度较低的 DataType(即 Integer)分配给精度较高的 DataType(即 0.0 Double)?
那么为什么会偏离依赖属性的基本编程概念呢?
【问题讨论】:
-
您可能期望这是,但事实并非如此。您必须分配预期的类型。如果是
double,则分配 3.0 或 (double)3。 -
@bash.d:我知道,但为什么会这样。将整数分配给 double 是合法的。
-
我经常遇到这个错误,以至于我最终编辑了我的代码 sn-ps 以获取依赖项和附加属性,以便默认值始终为
default($type$)... -
@ThomasLevesque:你如何解释如何改变它?
-
@NikhilAgrawal,使用代码 sn-ps 管理器(从工具菜单中),找到 NetFX30 sn-ps(
propa和propdp);它们通常位于 C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC#\Snippets\1033\NetFX30 中。编辑它们以删除defaultValue文字声明,并将$defaultValue$替换为default($type$)
标签: c# wpf vb.net dependency-properties attached-properties