Reputation: 5022
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
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
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
Reputation: 9704
You were just missing the text argument?
public override string Text
{
get { return Text.Replace(",", Text); }
set { Text = value; }
}
Upvotes: -1
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