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; }
}
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>
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
- http://blog.ningzhang.org/2008/11/dependencyproperty-validation-coercion.html
- http://msdn.microsoft.com/en-us/library/ms745795.aspx#Validation_Callbacks
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.
You were just missing the text argument?
public override string Text
{
get { return Text.Replace(",", Text); }
set { Text = value; }
}
精彩评论