命令触发后如何使用 MVVM 清除文本框

Mar*_*nom 4 c# data-binding wpf textbox mvvm

我的主窗口上有一个文本框控件。

<Grid>
        <TextBox x:Name="messageBox" Margin="252,89,277,300">
            <TextBox.InputBindings>
                <KeyBinding Key="Enter"
                            Command="{Binding TextCommand}"
                            CommandParameter="{Binding Text, ElementName=messageBox}"/>
            </TextBox.InputBindings>
        </TextBox>
    </Grid>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我已将Enter密钥绑定到当我单击 Enter 时,它会提示一个 MessageBox,其中包含我在 TextBox 中提供的文本。我的问题是..按回车后如何清除文本框?我不想在控件上调用事件,因为这会违背 MVVM 的目的,它还会弄乱我的 MainWindow.cs

正如您所看到的,我已经在主窗口中设置了 DataContext,如下所示。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ServerViewModel();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 ServerViewModel.cs

class ServerViewModel : INotifyPropertyChanged
    {
        public TextBoxCommand TextCommand { get; }
        public ServerViewModel()
        {
            TextCommand = new TextBoxCommand(SendMessage);
        }

        private void SendMessage(string parameter)
        {
            MessageBox.Show(parameter);
            parameter = "";
        }


        public event PropertyChangedEventHandler PropertyChanged;
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
Run Code Online (Sandbox Code Playgroud)

还有命令是否值得一看。

class TextBoxCommand : ICommand
    {
        public Action<string> _sendMethod;

        public TextBoxCommand(Action<string> SendMethod)
        {
            _sendMethod = SendMethod;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            _sendMethod.Invoke((string)parameter);
        }

        public event EventHandler CanExecuteChanged;
    }
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以将 TextBox 绑定到 ViewModel 上的属性,然后只需将该属性设置为空即可重置 TextBox。

绑定:

<TextBox x:Name="messageBox" Text="{Binding TextBoxInput, Mode=TwoWay}">
Run Code Online (Sandbox Code Playgroud)

ViewModel 中的新属性:

    public string TextBoxInput
    {
        get { return _textBoxInput; }
        set
        {
            _textBoxInput = value;
            OnPropertyChanged(nameof(TextBoxInput));
        }
    }
    private string _textBoxInput;
Run Code Online (Sandbox Code Playgroud)

此处重置文本框:

    private void SendMessage(string parameter)
    {
        MessageBox.Show(parameter);
        TextBoxInput = "";
    }
Run Code Online (Sandbox Code Playgroud)