聚焦时清除文本框

时间:2012-04-21 10:03:17

标签: wpf mvvm textbox clear

如何在聚焦时清除TextBox?我想以MVVM的方式做到这一点。如果它有意义 - 我的TextBox控件的Text属性绑定了ViewModel中的一些属性。 TextBox显示为“50,30zł”。用户选择文本,删除文本和编写新文本是不舒服的,因此我想在Texbox聚焦时清除旧文本。

3 个答案:

答案 0 :(得分:8)

您可以编写自己的行为甚至控制。 我将尝试解释第一个:

首先,您应该添加对 System.Windows.Interactivity 程序集的引用。

然后创建一个类(这将是行为)并从 System.Windows.Interactivity.Behavior<中导出它。 System.Windows.Controls.TextBox> ,其中模板化(泛型类型)参数是一个控件,应该按照我的描述行事。

例如:

class ClearOnFocusedBehavior : System.Windows.Interactivity.Behavior<System.Windows.Controls.TextBox>
{
    private readonly RoutedEventHandler _onGotFocusHandler = (o, e) =>
                                                        {
                                                            ((System.Windows.Controls.TextBox) o).Text =
                                                                string.Empty;
                                                        };

    protected override void OnAttached()
    {
        AssociatedObject.GotFocus += _onGotFocusHandler;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.GotFocus -= _onGotFocusHandler;
    }
}

接下来,将以下引用声明放在父窗口中的xaml

<Window x:Class="ManagementSolution.Views.UpdatePersonsWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
    //namespace with ur behaviors
    xmlns:behaviors="clr-namespace:ManagementSolution.Helper.Behaviours"
    //...
</Window>

最后将行为添加到适当的UI元素(在我们的例子中为TextBox):

<TextBox x:Name="PersonFirstNameTextBox"
             Grid.Column="1"
             Margin="5,0"
             HorizontalAlignment="Stretch"
             VerticalAlignment="Center"
             Style="{StaticResource TextBoxValidationStyle}"
             TextWrapping="Wrap"
             d:LayoutOverrides="Width, Height">
        //behavior added as the content
        <i:Interaction.Behaviors>   
            <behaviors:ClearOnFocusedBehavior /> 
        </i:Interaction.Behaviors>
        <TextBox.Text>
            <Binding Path="PersonFirstName"
                     UpdateSourceTrigger="PropertyChanged"
                     ValidatesOnDataErrors="True">
                <!--
                    <Binding.ValidationRules>
                    <rules:SingleWordNameValidationRule />
                    </Binding.ValidationRules>
                -->
            </Binding>
        </TextBox.Text>
    </TextBox>

答案 1 :(得分:0)

textBox1.Clear();

它清除textBox中的内容

答案 2 :(得分:0)

@Dmitry Martovoi的答案很棒。

这是使用附加属性(而不是混合行为)的相同解决方案。附加行为可以实现更简单的XAML,但不那么简单的C#,而Blend行为则相反。

XAML:

behaviors:MyTextBox.MyClearOnFocusedIfTextEqualsSearch="True"添加到TextBox,以便在收到焦点时将其清除,并且它包含Search

<Window x:Class="MyApp.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"
        xmlns:behaviors="clr-namespace:MyApp">
    <StackPanel Margin="10">
        <!-- GotFocus="TextBox_GotFocus" -->
        <TextBox x:Name="MyTextBox" 
                 behaviors:MyTextBox.MyClearOnFocusedIfTextEqualsSearch="True" 
                 HorizontalAlignment="Left" 
                 Text="Search" 
                 MinWidth="96" ></TextBox>  
    </StackPanel>
</Window>

附属物:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace MyApp
{
    public class MyTextBox : DependencyObject
    {
        public static readonly DependencyProperty MyClearOnFocusedIfTextEqualsSearchProperty = DependencyProperty.RegisterAttached(
            "MyClearOnFocusedIfTextEqualsSearch",
            typeof (bool),
            typeof(MyTextBox),
            new PropertyMetadata(default(bool), PropertyChangedCallback));

        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var textBox = dependencyObject as TextBox;
            if (textBox != null)
            {
                if ((bool)dependencyPropertyChangedEventArgs.NewValue == true)
                {
                    textBox.GotFocus += textBox_GotFocus;
                }
            }
        }

        private static void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox != null)
            {
                if (textBox.Text.ToLower() == "search")
                {
                    textBox.Text = "";
                }
            }
        }

        public static void SetMyClearOnFocusedIfTextEqualsSearch(DependencyObject element, bool value)
        {
            element.SetValue(MyClearOnFocusedIfTextEqualsSearchProperty, value);
        }

        public static bool GetMyClearOnFocusedIfTextEqualsSearch(DependencyObject element)
        {
            return (bool)element.GetValue(MyClearOnFocusedIfTextEqualsSearchProperty);
        }
    }
}

我花了几分钟写下这个附加行为。 ReSharper有一个很棒的宏,如果你输入attachedProperty,它会为你填写大部分代码。