聚焦时清除文本框

Arv*_*gen 2 wpf textbox mvvm clear

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

Dzm*_*voi 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,将以下引用声明放在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>
Run Code Online (Sandbox Code Playgroud)

最后将行为添加到适当的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>
Run Code Online (Sandbox Code Playgroud)