Yuval Levy
Yuval Levy

Reputation: 2516

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

Upvotes: 0

Views: 2264

Answers (4)

Shradha
Shradha

Reputation: 90

Checkout this link, even I was facing somewhat similar problem Solution in this link can me modified according to your condition.

Add percent sign "%" to any input text in wpf TextBox when the user insert a text

Upvotes: 0

mm8
mm8

Reputation: 169150

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, e.g.:

<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; }
}

Upvotes: 0

Mike Eason
Mike Eason

Reputation: 9713

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

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

Check out this tutorial.

Upvotes: 0

mm8
mm8

Reputation: 169150

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;
    }
}

Upvotes: 1

Related Questions