ar.gorgin
ar.gorgin

Reputation: 5022

Override text property of textbox

How do I override the text property in a textbox in WPF?

I want this code in WPF:

 public override string Text
 {
        get { return Text.Replace(",", ""); }
        set { Text = value; }
 }

Upvotes: 4

Views: 5209

Answers (4)

Dabblernl
Dabblernl

Reputation: 16131

While the upvoted answers are correct, there is a much simpler approach: as the Text property of TextBox is bound to a property of an underlying class (usually in the Viewmodel) simply take care to provide the replacement in the underlying class.

Upvotes: 0

Phil Wright
Phil Wright

Reputation: 22946

If you are data binding against the TextBox.Text property then another possible approach is to move the logic away from the control itself and place it in a converter. Your converter would look something like this...

public class CommaReplaceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, 
                              object parameter, CultureInfo culture)
    {
        return value.ToString().Replace(",", "");
    }
}

And data binding something like this...

<TextBox Text="{Binding XXX, Converter={StaticResource CRC}" />

...where the static resource is defined as...

<Window.Resources>
    <CommaReplaceConverter x:Key="CRC"/>
</Windows.Resources>

Upvotes: 3

Alex Hope O&#39;Connor
Alex Hope O&#39;Connor

Reputation: 9704

You were just missing the text argument?

public override string Text 
    { 
        get { return Text.Replace(",", Text); } 
        set { Text = value; } 
    } 

Upvotes: -1

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

Text is a dependency property. If you have derived a class from TextBox then you need to override the metadata and provide your validation callbacks

See

Upvotes: 2

Related Questions