How to clear a TextBox in MVVM?

13,602

If the text is part of your data layer and application logic, a string should exist in your Model or ViewModel and be cleared from there

For example,

<TextBox Text="{Binding NewNote}" ... />

and

void NotesEntered(int oid)
{
    SaveNewNote(oid);

    NewNote = string.Empty;
}

If it's part of the UI layer only, it should just be cleared with code-behind. It's perfectly acceptable to have UI-specific logic in the code-behind the UI, as that still maintains the separation of layers.

NewNoteTextBox_LostFocus(object sender, EventArgs e)
{
    (sender as TextBox).Text = string.Empty;
}

NewNoteTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Keys.Enter)
        (sender as TextBox).Text = string.Empty;
}
Share:
13,602
user2170838
Author by

user2170838

Updated on June 04, 2022

Comments

  • user2170838
    user2170838 almost 2 years

    I have a TextBox in a DataTemplate declared as follows:

    <TextBox Grid.Row="1" Grid.Column="1" Margin="0,4,0,0">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="LostFocus">
            <cmd:EventToCommand Command="{Binding DataContext.NotesEnteredCommand,
                                RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
                <cmd:EventToCommand.CommandParameter>
                    <MultiBinding Converter="{StaticResource SimpleMultiValueConverter}">
                        <Binding Path="Row.OID" />
                        <Binding Path="Text" RelativeSource="{RelativeSource FindAncestor, AncestorType=TextBox}" />
                    </MultiBinding>
                </cmd:EventToCommand.CommandParameter>
            </cmd:EventToCommand>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding DataContext.NotesEnteredCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
            <KeyBinding.CommandParameter>
                <MultiBinding Converter="{StaticResource SimpleMultiValueConverter}">
                    <Binding Path="Row.OID" />
                    <Binding Path="Text" RelativeSource="{RelativeSource FindAncestor, AncestorType=TextBox}" />
                </MultiBinding>
            </KeyBinding.CommandParameter>
        </KeyBinding>
    </TextBox.InputBindings>
    

    What this TextBox basically does is execute a MVVM-Light RelayCommand when the Enter key is pressed or when losing focus.

    My problem is that I cannot figure out a way in MVVM to clear the TextBox's Text value through XAML in the above two scenarios. It's very easy with in code-behind, but I can't figure it out in MVVM.

    Any ideas?