c# - 我的命令触发后如何使用 MVVM 清除我的文本框
问题描述
我的 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 时,我已将密钥绑定到它会提示一个带有我在 TextBox 中提供的文本的 MessageBox。我的问题是..按回车后如何清除文本框?我不想在控件上调用事件,因为这会破坏 MVVM 的目的,它也会弄乱我的 MainWindow.cs
如您所见,我已经像这样在 MainWindow 中设置了 DataContext ..
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。
绑定:
<TextBox x:Name="messageBox" Text="{Binding TextBoxInput, Mode=TwoWay}">
ViewModel 中的新属性:
public string TextBoxInput
{
get { return _textBoxInput; }
set
{
_textBoxInput = value;
OnPropertyChanged(nameof(TextBoxInput));
}
}
private string _textBoxInput;
文本框在这里重置:
private void SendMessage(string parameter)
{
MessageBox.Show(parameter);
TextBoxInput = "";
}
推荐阅读
- c++ - CMake 谷歌测试
- python - 跨不同系统(机器)使用相同 random_state 的 Sklearn 不同结果
- laravel - 如何将用户发送回 Laravel 中的预期页面
- reactjs - 在 Visual Studio Code 中自动导入 React 组件
- python - 从目录中导入时,点表示什么?
- typescript - 条件类型和注入接口?
- azure-application-insights - 如何在单个事件中添加名称数组?
- python - 如何使用 3d numpy 索引数组来检索 4d 数组中的相应值?
- angular - 如何为 IE11 构建生产 Angular8 应用程序
- deep-learning - 在 Python 中构建推理系统以获取程序建议