在我的视图中,我有一个按钮。如何使用DelegateCommand将View中的信息传递给ViewModel?
当用户点击这个按钮时,我想让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>
但是,我在我的视图模型,“保存()” DelegateCommand方法不传递任何参数,所以如何从在这一点上的看法得到的数据?
#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
我实际上通过将TextBox绑定到ViewModel属性(INotifyPropertyChanged)来解决我的问题,当然,Save()命令可以访问哪个值,但是您的建议非常有趣,它将检查它们。 – 2009-05-28 11:28:01
Matt的解决方案肯定赢得了访问单独的绑定值的具体(合理常见)用例:在ItemsControl中执行的命令。在这里,一个按钮,比如'ListView'中的按钮可以使用它的'DataContext'作为参数,并且按钮被点击的项目和命令一起被传递。很难计算出许多项目中的哪一个按钮被点击。 – 2015-05-13 10:19:30
请注意,通用的'DelegateCommand'有一个重要的限制(在运行时没有被选中 - 编译器不会抱怨):不能使用值类型作为参数。官方建议是使用可以为空的值类型(允许),并在使用之前检查它是否包含值(https://msdn.microsoft.com/en-us/library/gg431410%28v=pandp.50%29 .aspx - 请参阅“备注”部分)。 –
2015-05-13 10:23:43