У меня есть мой MainWindow с элементом управления TextBox.
<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>
И как вы может видеть, что я связал ключ Enter
, когда я нажимаю Enter, он объявляет MessageBox текстом, который я предоставил в TextBox. Вопрос в том, как .. Как очистить текстовое поле после нажатия клавиши ввода? Я не хочу вызывать событие на элементе управления, потому что это победит цель MVVM, оно также загромождит мой MainWindow.cs
Как вы можете видеть, я установил DataContext в свой MainWindow так вот ..
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ServerViewModel();
}
}
И вот мой 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));
}
}
И команда, если это стоит посмотреть.
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;
}
Вы можете привязать свой TextBox к свойству в ViewModel и сбросить TextBox, просто установив свойство в пустое.
Связывание:
Новое свойство в ViewModel:
Здесь TextBox сбрасывается здесь: