2012-02-16 114 views
2

只是想知道这是否是一种好的做法,或者从长远来看是否会造成任何麻烦。说实话,我很惊讶,它甚至可以工作 - 它可以完成这项工作,但我不确定这是否有风险。隐藏依赖属性

基本上,我们创建了一个NumericTextBoxTextBox派生,我们与new关键字从文本中删除逗号推翻了Text属性:

public class NumericTextBox : TextBox 
{ 
    public new string Text 
    { 
     get 
     { 
      return base.Text.Replace(",", String.Empty); 
     } 
     set 
     { 
      base.Text = value; 
     } 
    } 
} 

我不喜欢它是什么,我知道Text是一个依赖属性,我们要覆盖它,但令人惊讶的,我们仍然可以给它绑定在XAML:

<this:NumericTextBox x:Name="textBox" 
        Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=SomeText, Converter={StaticResource debugConverter}}" /> 

然后在C#中,当我们呼吁textBox.Text我们确实得到没有逗号的值。

你们认为什么?

回答

0

也许你应该add your class as an owner of the dependency property并覆盖getter和setter有:

public class NumericTextBox : TextBox 
{ 
    public NumericTextBox() { } 
    public static readonly DependencyProperty NumericTextProperty = TextBox.TextProperty.AddOwner(typeof(NumericTextBox), new PropertyMetadata(null)); 
    public new string Text 
    { 
     get { return ((string)this.GetValue(NumericTextProperty)).Replace(",", String.Empty); } 
     set { this.SetValue(NumericTextProperty , value); } 
    } 
} 

此外,还可以overriding the metadata of the dependency property的可能性,在自定义的验证回调方法挂钩。

您的方法不起作用,因为WPF实际上并未使用类属性来更改值,而是依赖项属性系统。它只是像在属性设置器中那样调用SetValue方法。你可以在setter中设置一个断点并改变gui中的bound属性来尝试它。 setter断点永远不会被打中。但是你可以挂钩依赖属性元数据提供的事件。

+0

它抱怨不使用'新'关键字,如果隐藏是有意的,我试着添加它,我得到一个异常。现在可能为Text属性或其他东西工作。 – Carlo 2012-02-16 21:41:55

+0

感谢您的额外信息。但是,这是一种好的做法,还是应该避免?如果你知道为什么,那也会有很大的帮助。 – Carlo 2012-02-16 21:46:49

+0

该代码是否可以为您运行?在这里,我得到一个运行时异常:http://screencast.com/t/EbiYg14f – Carlo 2012-02-16 22:00:50