简体   繁体   English

删除文本框绑定的最后一个字符

[英]Removing last character of textbox binding

I am running into some problem binding a textbox to a property in my view. 我在将文本框绑定到视图中的属性时遇到了一些问题。 The binding works perfectly until I try to remove the last character. 绑定工作完美,直到我尝试删除最后一个字符。 The cursor moves back but the last character is still there in the textbox and in the property it is bind to. 光标向后移动,但最后一个字符仍在文本框中,并且在其绑定的属性中。

<TextBox Grid.Column="0" Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

And the Propety itself 而Propety本身

    public string SearchText
    {
        get { return _searchText; }
        set 
        {
            if (searchText != value)
            {
                if (value != "")
                {
                    Debug.WriteLine("Typed Value " + value);
                    searchText = value;
                }

            }
        }
    }

This outputs to: "Typed Value F" if I try to completely erase Foo from the textbox. 如果我尝试从文本框中完全擦除Foo,则输出为:“ Typed Value F”。 On the last press of backspace, the cursor moves back but the character is not removed. 在最后一次按Backspace键时,光标会向后移动,但不会删除字符。

How could i solve this? 我该如何解决?

Your conditional statement prevents the new value from being set. 您的条件语句阻止设置新值。

if (value != "") //if value is NOT an empty string
{
   Debug.WriteLine("Typed Value " + value);
   searchText = value;
}

Therefore when it is an empty string (ie last character deleted), you're not calling searchText = value therefore not setting the new value. 因此,当它是一个空字符串(即删除了最后一个字符)时,您不会调用searchText = value因此不会设置新值。 I can't see a reason for having that check in the code you've shown so you can either remove it or make sure you're always setting the value outside that block. 我看不出在您显示的代码中进行检查的原因,因此您可以删除它或确保始终在该块之外设置该value

Removing everything from TextBox means setting Text to string.Empty or "". 从TextBox中删除所有内容意味着将Text设置为string.Empty或“”。

Now you dont let the property to be set to empty therefore your last character always stays in TextBox. 现在,您不要将属性设置为空,因此您的最后一个字符始终停留在TextBox中。

Just get ride of if (value != "") 只要乘上if(值!=“”)

Look at your code again 再看看你的代码

if (value != "")
{
   Debug.WriteLine("Typed Value " + value);
   searchText = value;
}

If value == "" searchText is not assigned' 如果值==“”未分配searchText'

if (value != "")
{
   Debug.WriteLine("Typed Value " + value);      
}
searchText = value;

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

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