简体   繁体   English

c#wpf文本框-向输入文本框添加文本

[英]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. 当用户插入文本时,我想在wpf TextBox中的任何输入文本中添加百分号“%”。

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% 因此,当用户输入数字时,会将百分号添加到输入框中的任何数字,例如:5将在文本框中显示为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... 但是当用户插入输入时,它对TextBox无效。

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: 您可以使用一个标志来决定是否应该在事件处理程序中实际设置Text属性:

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 . 如果要绑定 Text属性,则可以使用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... 但是当用户插入输入时,它对TextBox无效。

You need to define the source property and set the DataContext of the TextBox to the class where it is defined, eg: 您需要定义source属性,并将TextBoxDataContext设置为定义该属性的类,例如:

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

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

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