【问题标题】:Default Text in silverlight search text boxSilverlight 搜索文本框中的默认文本
【发布时间】:2011-06-09 20:04:23
【问题描述】:

我需要 Silverlight 文本框中的功能,类似于 stalkoverflow 中“标题”文本框中的功能。当文本框中没有文本时,它应该显示“搜索”。当用户单击文本框时,文本框文本应该为空,如果文本为空,则文本框失去焦点,然后显示“搜索”。我写了以下代码,但是有没有可以处理所有可能条件的代码?

private void txtAvailable_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
            txtAvailable.Text = "";
 }

 private void txtAvailable_LostFocus(object sender, RoutedEventArgs e)
 {
            if (txtAvailable.Text.Trim() == "")
                txtAvailable.Text = "Search";
 }

【问题讨论】:

    标签: silverlight search default


    【解决方案1】:

    您可以使用 Textbox GotFocus 和 LostFocus 事件 - 它们应该足够通用以覆盖您的所有潜力。

    当您想在每次击键时进行搜索时,特殊性就出现了 - 您必须启用和禁用对这些事件的搜索。

        private bool IsBusy
        {
            get;
            set;
        }
    
        private bool CanSearch
        {
            get;
            set;
        }
    
        public Constructor()
        {
            InitializeComponent();
    
            this.IsBusy = false;
    
            txtSearch.GotFocus += new RoutedEventHandler( txtSearch_GotFocus );
            txtSearch.LostFocus += new RoutedEventHandler( txtSearch_LostFocus );
            txtSearch.KeyUp += new System.Windows.Input.KeyEventHandler( txtSearch_KeyUp );
            txtSearch.Text = "Search »";
        }
    
        private void txtSearch_LostFocus( object sender, RoutedEventArgs e )
        {
            if( string.IsNullOrEmpty( txtSearch.Text ) )
            {
                CanSearch = false;
                txtSearch.Text = "Search »";
            }
        }
    
        private void txtSearch_GotFocus( object sender, RoutedEventArgs e )
        {
            txtSearch.Text = string.Empty;
            CanSearch = true;
        }
    
        private void OnFilterCommand()
        {
            try
            {
                if( !IsBusy && CanSearch )
                {
                    AppMessages.FilterAssetMessage.Send( txtSearch.Text );
                }
            }
            catch( Exception ex )
            {
                // Notify user if there is any error
                AppMessages.RaiseErrorMessage.Send( ex );
            }
        }
    
        private void txtSearch_KeyUp( object sender, System.Windows.Input.KeyEventArgs e )
        {
            OnFilterCommand();
        }
    

    【讨论】:

    • 忙碌是什么意思?!您只是设置 false,而不是使用 after。
    • True.. 我认为我从中提取的代码在执行其他操作并且不想进行过滤时使用了 Busy 标志。随意从你自己的东西中删除它。
    【解决方案2】:

    如果您熟悉 WPF 以及 WPF 和 Silverlight 之间的区别,请查看扩展的 WPF 工具包中的 WatermarkTextBox:

    http://wpftoolkit.codeplex.com/wikipage?title=WatermarkTextBox&referringTitle=Home

    源可用,因此您可以尝试将该控件移植到 Silverlight。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多