使用Textbox模拟Facebook搜索的问题Textchanged当文本为空时的事件

时间:2014-03-28 03:58:14

标签: c# textbox textchanged

我试图模仿Facebook每次在搜索框中输入密钥时的搜索方式。我目前面临的问题是,当我想要清除搜索框或我尝试手动删除所有文本时。它仍会将默认文本(搜索)作为搜索条目触发。非常感谢,谢谢!

private void SearchTB_TextChanged(object sender, TextChangedEventArgs e)
  {
    int keyword_length = ((TextBox)sender).Text.Length;


    if (keyword_length == 0)
    {
      SearchTB.Text = "Search";
      myButton.Text = "Cancel";
     }

     //  When user starts to enter in text
     if (keyword_length > 0)
       {
         SearchTB.Text = "";
         myButton.Text = "Clear";
       }

     // Search when 3 chars has been entered into Searchbox
     if (keyword_length > 2)
       {
         keyword = ((TextBox)sender).Text;
         SearchBook(this.keyword);
        }
    }

private void myButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        if (myButton.Text == "Clear")
        {
           SearchTB.Text = "Search";
           myButton.Text = "Cancel";
        }
        else
        {
            if (cancelButton.Text == "Cancel")
            {
              Debug.WriteLine("This is cancel button");
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

正如我所看到的,你正在使用WPF(没有标签,但名称空间属于WPF),所以你可以在XAML中这样做:

<Grid>
    <TextBox x:Name="SearchTB" />
    <TextBlock x:Name="SearchBlock" Text="Search" IsHitTestVisible="False"
               VerticalAlignment="Center" />
</Grid>

在代码中

if (keyword_length == 0)
{
  SearchBlock.Visibility = Visibility.Visible;
  myButton.Text = "Cancel";
}
else
{
  SearchBlock.Visibility = Visibility.Hidden;
  myButton.Text = "Clear";
}

因此,您隐藏的文字图块因IsHitTestVisible="False"而无法点击,只有在搜索文字为空时才可见。