簡體   English   中英

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

[英]c# wpf textbox - adding a text to input TextBox

當用戶插入文本時,我想在wpf TextBox中的任何輸入文本中添加百分號“%”。

因此,當用戶輸入數字時,會將百分號添加到輸入框中的任何數字,例如:5將在文本框中顯示為5%0-0%100-100%

我嘗試了以下代碼:

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

和:

public int AddPercentSign{ get; set; }

和:

TextBoxInputValue.DataContext = this;

但是當用戶插入輸入時,它對TextBox無效。

我怎樣才能達到那個結果?

謝謝

您可以使用一個標志來決定是否應該在事件處理程序中實際設置Text屬性:

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

如果要綁定 Text屬性,則可以使用StringFormat

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

查看教程。

但是當用戶插入輸入時,它對TextBox無效。

您需要定義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