【发布时间】:2018-11-13 00:45:43
【问题描述】:
所以我的 MainWindow.xaml 上有一个文本框。
<Window x:Class="HelloICommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="337,195,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120">
<TextBox.InputBindings>
<KeyBinding Command="{Binding }" Key="Enter"></KeyBinding>
</TextBox.InputBindings>
</TextBox>
</Grid>
</Window>
如您所见,我想将我的回车键绑定到我可以点击回车的位置,它会显示一个消息框,其中包含文本框中的文本。
在我的 MainWindow.cs 中,我像这样设置数据上下文。
public MainWindow()
{
InitializeComponent();
DataContext = new ServerViewModel();
}
然后我有了实际的 ServerViewModel,里面还有其他所有东西 这就是我遇到问题的地方,如何将文本从 TextBox 传递到该方法,以便每次单击 Enter 时都能看到消息。
class ServerViewModel
{
private TextBoxCommand textCommand { get; private set; }
public ServerViewModel()
{
textCommand = new TextBoxCommand(SendMessage);
}
//How do I pass the text from the textbox as a parameter here?
public void SendMessage()
{
MessageBox.Show("");
}
}
ICommand 接口
class TextBoxCommand : ICommand
{
public Action _sendMethod;
public TextBoxCommand(Action SendMethod)
{
_sendMethod = SendMethod;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
}
public event EventHandler CanExecuteChanged;
}
【问题讨论】: