gpt4 book ai didi

wpf - 如何使用 DelegateCommand 将信息从 View 传递到 ViewModel?

转载 作者:行者123 更新时间:2023-12-04 00:00:34 25 4
gpt4 key购买 nike

在我看来,我有一个按钮。

当用户单击此按钮时,我希望 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()”方法不传递任何参数,那么我该如何从 View 中获取数据呢?
#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

最佳答案

查看 this MSDN article by Josh Smith .在其中,他展示了他称为 RelayCommand 的 DelegateCommand 的变体,并且 RelayCommand 上的 Execute 和 CanExecute 委托(delegate)接受对象类型的单个参数。

使用 RelayCommand,您可以通过 CommandParameter 将信息传递给代表:

<Button Command="{Binding SaveCommand}" 
CommandParameter="{Binding SelectedItem,Element=listBox1}" />

更新

this article ,似乎有一个通用版本的 DelegateCommand 以类似的方式接受参数。您可能想尝试将 SaveCommand 更改为 DelegateCommand<MyObject>并更改您的 Save 和 CanSave 方法,以便它们采用 MyObject 参数。

关于wpf - 如何使用 DelegateCommand 将信息从 View 传递到 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/920172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com