【问题标题】:Processing WPF textbox input events处理 WPF 文本框输入事件
【发布时间】:2011-05-28 17:21:03
【问题描述】:

我有一个带有默认文本的文本框,例如“输入名称”

一旦用户开始输入一些文本或关注文本框(使用 MouseEnter 或 KeyboardFocus),我希望显示默认文本并且只显示用户输入。

但如果用户在没有任何输入的情况下将其留空,然后使用 MouseLeave 或 LostKeyboardFocus,我希望重新出现默认文本。

我认为这是我正在尝试实现的最简单的模式,但还没有完全实现。

如何以优雅的标准方式处理它?我是否需要使用自定义变量来跟踪此事件流中的状态或 WPF 文本框事件就足够了?

这样做的伪代码示例会很棒。

【问题讨论】:

    标签: .net wpf


    【解决方案1】:

    这里有一些伪代码:

    textBox.Text = "Please enter text...";
    ...
    private string defaultText = "Please enter text...";
    
    GotFocus()
    {
      if (textBox.Text == defaultText) textBox.Text = string.Empty;
    }
    
    LostFocus()
    {
      if (textBox.Text == string.Empty) textBox.Text = defaultText;
    }
    

    【讨论】:

    • 太棒了。我是 WPF 和输入事件的新手。这个简单的模式有效。也将此应用于鼠标事件。
    【解决方案2】:

    您可以设置样式触发器来设置键盘失去焦点上的默认文本,如下所示:

    <Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" >
    <Window.Resources>
        <Style x:Key="textboxStyle" TargetType="{x:Type TextBox}" >
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocused" Value="False">
                    <Trigger.Setters>
                        <Setter Property="Text" Value="Enter text" />
                    </Trigger.Setters>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox Name="textBoxWithDefaultText" Width="100" Height="30"  Style="{StaticResource textboxStyle}"  TextChanged="textBoxWithDefaultText_TextChanged"/>
        <TextBox Name="textBoxWithoutDefaultText" Width="100" Height="30"  />
    
    </StackPanel>
    

    但是当您使用键盘在 TextBox 中输入文本时,本地值优先于样式触发器,因为文本是依赖属性。因此,为了使样式触发器在下次 TextBox 文本为空时起作用,请在后面添加以下代码:

        private void textBoxWithDefaultText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if(textBoxWithDefaultText.Text == "")
                textBoxWithDefaultText.ClearValue(TextBox.TextProperty);
        }
    

    【讨论】:

      猜你喜欢
      • 2012-01-10
      • 2010-12-27
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多