【问题标题】:How do I clear my TextBox using MVVM after my Command fires我的命令触发后如何使用 MVVM 清除我的文本框
【发布时间】:2018-06-03 17:48:31
【问题描述】:

我的 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;
    }

【问题讨论】:

  • "MessageBox.Show(参数);"在 MVVM 中,在 VM 内部有 view 的引用是不好的。

标签: c# wpf mvvm data-binding textbox


【解决方案1】:

您可以将 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;

TextBox 在这里重置:

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

【讨论】:

  • “你可以将你的 TextBox 绑定到你的 ViewMode 上的一个属性”这很奇怪,因为 MVVM 就是关于绑定的。
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多