在我的视图中,我有一个按钮。
当用户点击此按钮时,我希望ViewModel将TextBlock的上下文保存到数据库中。
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
<TextBlock Text="{Binding FirstName}"/>
<TextBox Text="Save this text to the database."/>
<Button Content="Save" Command="{Binding SaveCommand}"/>
</StackPanel>
然而,在我的ViewModel中的DelegateCommand中,“Save()”方法不会传递任何参数,那么在这一点上我如何从视图获取数据?
#region DelegateCommand: Save
private DelegateCommand saveCommand;
public ICommand SaveCommand
{
get
{
if (saveCommand == null)
{
saveCommand = new DelegateCommand(Save, CanSave);
}
return saveCommand;
}
}
private void Save()
{
TextBox textBox = ......how do I get the value of the view's textbox from here?....
}
private bool CanSave()
{
return true;
}
#endregion
ItemsControl
内执行的命令。在这里,例如,在ListView
中的按钮可以使用其DataContext
作为参数,并将被点击的项目随命令一起传递。否则很难确定哪个项目的按钮被点击了。 - Bob SammersDelegateCommand<T>
有一个重要的限制(直到运行时才会发现 - 编译器不会抱怨):您不能使用值类型作为参数。官方建议是使用可空的值类型(允许使用),并在使用之前检查其是否包含值(https://msdn.microsoft.com/zh-cn/library/gg431410%28v=pandp.50%29.aspx - 见“备注”部分)。 - Bob Sammers