To clear or programmatically set the TextBox’s content from your VM, you don’t need to touch the view/XAML at all – just update the bound property and raise PropertyChanged. The UI will pick up the new value.
1. Make sure your VM property raises change notifications
public class ChatViewModel : INotifyPropertyChanged
{
private string _chatInputText = string.Empty;
public string ChatInputText
{
get => _chatInputText;
set
{
if (_chatInputText != value)
{
_chatInputText = value;
OnPropertyChanged(); // notify the UI
}
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
// Example command to send and then reset:
public ICommand SendCommand => new RelayCommand(ExecuteSend);
private void ExecuteSend()
{
// 1. send ChatInputText to your service...
// 2. clear it:
ChatInputText = string.Empty;
}
}
If you’re using MVVM helpers like CommunityToolkit.MVVM, you can decorate with [ObservableProperty] to get all of the above auto-generated.
2. Wire up your Send button in XAML
<StackPanel Orientation="Horizontal">
<TextBox
Text="{Binding ChatInputText,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
… />
<Button Content="Send"
Command="{Binding SendCommand}" />
</StackPanel>
When your ExecuteSend() runs, setting
ChatInputText = string.Empty;
will immediately clear the TextBox in the UI.
Key points
- Any time you assign
ChatInputText = "..." in the VM, the TextBox will update.
- Two-way binding pushes user edits back into the VM;
OnPropertyChanged pushes VM edits into the UI.
- You can call this reset from any VM method or command.