2012-02-16 75 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