【问题标题】:Numeric type as DependencyProperty作为 DependencyProperty 的数值类型
【发布时间】:2014-07-26 10:49:45
【问题描述】:

如何注册基于数值类型的自定义属性?

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

<nb:NumberBox FormatValue="{System:Int32}"/>

我敢肯定,这并不完美,但我真的不知道它是如何实现的。

更新:

基本上,我需要有一种方法来设置我的号码框的类型。例如,如果我需要使用Double NumberBox,我只需设置FormatValue="Double"

【问题讨论】:

  • 为什么要使用类型作为属性?也许有更好的方法?
  • 也许:) 但我不知道
  • 为什么不使用蒙版文本框?
  • default(Double) 以双精度返回 0。您希望 Type 对象作为您的默认属性值 -- typeof(Double)
  • 我同意@DanielA.White。你真正想解决什么问题?一旦你设置了 FormatValue 依赖属性,你打算用它做什么?如果我们知道最终结果,可能会有一个完全更好的解决方案,甚至可能不涉及额外的依赖属性。

标签: c# .net wpf dependency-properties


【解决方案1】:

第一个问题是在 DP 标识符的最后一个参数中提供的默认元数据不正确

代替

new UIPropertyMetadata(default(Double)),

应该是

new UIPropertyMetadata(typeof(Double))

第二个 XAML 中的问题。使用 x:Type 传递类型。

<nb:NumberBox xmlns:sys="clr-namespace:System;assembly=mscorlib"
              FormatValue="{x:Type sys:Int32}"/>

【讨论】:

【解决方案2】:

从这里http://msdn.microsoft.com/en-us/library/ee792002%28v=vs.110%29.aspx,类型是x:Int32x: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>

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多