简体   繁体   中英

c# wpf textbox - adding a text to input TextBox

I want to add percent sign "%" to any input text in wpf TextBox when the user insert a text.

So when the user will enter a number, will be added % sign to any number in the input box, for example: 5 will shown at the Text box as 5% 0 - 0% 100 - 100%

I tried the following code:

<TextBox x:Name="TextBoxInputValue" Text="{Binding AddPercentSign, UpdateSourceTrigger=PropertyChanged, StringFormat={}{0}%}" Style="{StaticResource @TextBoxStyle}" Width="100" Height="20"></TextBox>

and:

public int AddPercentSign{ get; set; }

and:

TextBoxInputValue.DataContext = this;

But it has no effect on the TextBox when the user insert an input...

How can I achieve that result?

Thank you

You could use a flag that decides whether you should actually set the Text property in the event handler:

private bool _handleEvent = true;
private void TextChanged(object sender, TextChangedEventArgs e)
{
    if (_handleEvent)
    {
        _handleEvent = false;
        MyTextBox.Text = MyTextBox.Text + "%$#";
        _handleEvent = true;
    }
}

If you are binding your Text property, you can use StringFormat .

<TextBox Text="{Binding SomeProperty, StringFormat={}{0}%}" />

Check out this tutorial.

But it has no effect on the TextBox when the user insert an input...

You need to define the source property and set the DataContext of the TextBox to the class where it is defined, eg:

<TextBox x:Name="textBox1" Text="{Binding SomeProperty, UpdateSourceTrigger=PropertyChanged, StringFormat='{}{0}%'}" />

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        textBox1.DataContext = this;
    }

    public int SomeProperty { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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