C# 作为DependencyProperty的数字类型
如何注册基于数字类型的自定义属性C# 作为DependencyProperty的数字类型,c#,.net,wpf,dependency-properties,C#,.net,Wpf,Dependency Properties,如何注册基于数字类型的自定义属性 public class NumberBox : TextBox { public static readonly DependencyProperty FormatProperty = DependencyProperty.Register("FormatValue", typeof(Type), typeof(NumberBox), new UIPropertyMetadata(default(Double))); p
public class NumberBox : TextBox
{
public static readonly DependencyProperty FormatProperty = DependencyProperty.Register("FormatValue", typeof(Type), typeof(NumberBox), new UIPropertyMetadata(default(Double)));
public Type FormatValue
{
get
{
return (Type)GetValue(FormatProperty);
}
set
{
SetValue(FormatProperty, value);
}
}
}
XAML
我敢肯定,这并不完美,但我真的不知道如何使它可行
更新:
基本上,我需要有一种方法来设置我的号码框的类型。例如,如果我需要使用
Double
NumberBox,我只需设置FormatValue=“Double”
第一个问题是DP标识符的最后一个参数中提供的默认元数据不正确
而不是
新建UIPropertyMetadata(默认值(双精度))
应该是
新的UIPropertyMetadata(typeof(Double))
第二个XAML版本。使用x:Type
传递类型
<nb:NumberBox xmlns:sys="clr-namespace:System;assembly=mscorlib"
FormatValue="{x:Type sys:Int32}"/>
从这里开始,类型是x:Int32
,x:Double
因此,您要使用:
<nb:NumberBox FormatValue="{x:Type x:Int32}"/>
一般来说,您必须在XAML中包含名称空间:
<Window ...
xmlns:ns="clr-namespace:MyNamepsace;assembly=MyAssembly"
>
<nb:NumberBox FormatValue="{x:Type ns:MyType}"/>
</Window>
为什么要使用类型作为属性?也许有更好的方法?也许:)但我不知道为什么不使用屏蔽文本框?default(Double)
将0
作为Double返回。您希望Type
对象作为默认属性值--typeof(Double)
。我同意@DanielA.White。你到底想解决什么问题?一旦设置了FormatValue依赖项属性,您打算如何处理它?如果我们知道最终结果,可能会有一个更好的解决方案,甚至可能不涉及额外的依赖属性。我的代码根本不起作用,我只是试图解决这个问题“@clcto-是的,这些原语在WPF 4.0之后可用。
<Window ...
xmlns:ns="clr-namespace:MyNamepsace;assembly=MyAssembly"
>
<nb:NumberBox FormatValue="{x:Type ns:MyType}"/>
</Window>