简体   繁体   English

覆盖文本框的文本属性

[英]Override text property of textbox

How do I override the text property in a textbox in WPF ? 如何覆盖WPF中文本框中的文本属性?

I want this code in WPF: 我想在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. 如果您是对TextBox.Text属性的数据绑定,那么另一种可能的方法是将逻辑从控件本身移开并将其放在转换器中。 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. Text是依赖属性。 If you have derived a class from TextBox then you need to override the metadata and provide your validation callbacks 如果从TextBox派生了一个类,则需要覆盖元数据并提供验证回调

See 看到

虽然upvoted答案是正确的,但有一个更简单的方法:因为TextBox的Text属性绑定到底层类的属性(通常在Viewmodel中),只需要在底层类中提供替换。

You were just missing the text argument? 你刚刚错过了文本参数?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM