如何使用程序创建的按钮在WPF MVVM中创建OnClick命令? [英] How do you create an OnClick command in WPF MVVM with a programmatically created button?
问题描述
我正在编写一个WPF应用程序,该程序以编程方式创建了一些按钮。如何在ViewModel中为按钮创建OnClick命令?我想添加一条命令,以使用ResetButton清除所有文本框。
I am writing a WPF application that programmatically creates a few buttons. How do you create an OnClick command for a button in the ViewModel? I would like to add a command to clear all TextBoxes with the ResetButton.
new StackPanel
{
Orientation = Orientation.Horizontal,
Children =
{
new Button { Name = "SendButton", Content = "Send", MinWidth = 50, MaxHeight = 30, Margin = new Thickness(5), Background = Brushes.DodgerBlue },
new Button { Name = "ResetButton", Content = "Reset", MinWidth = 50, MaxHeight = 30, Margin = new Thickness(5), Background = Brushes.DarkRed}
}
});
推荐答案
您是否可以访问视图模型创建堆栈面板?
Do you have access to the view model as you are creating the Stack Panel?
如果是这样,您的视图模型将公开一个命令:
If so, you have your View Model expose a Command:
var myViewModel = (MyViewModel)this.DataContext;
Button sendButton = new Button
{
Name = "SendButton",
Command = myViewModel.SendCommand,
// etcd
}
在您的视图模型中:
class MyViewModel : INotifyPropertyChanged
{
private class SendCommand : ICommand
{
private readonly MyViewModel _viewModel;
public SendCommand(MyViewModel viewModel)
{
this._viewModel = viewModel;
}
void ICommand.Execute(object parameter)
{
_viewModel.Send();
}
bool ICommand.CanExecute(object p)
{
// Could ask the view nodel if it is able to execute
// the command at this moment
return true;
}
}
public ICommand SendCommand
{
get
{
return new SendCommand(this);
}
}
internal void Send()
{
// Invoked by your command class
}
}
本示例为此命令创建了一个新类。多次完成此操作后,您可能会看到一个模式,并将其包装在通用实用程序类中。有关示例,请参见 http://www.wpftutorial.net/delegatecommand.html ,或使用任何众多的WPF扩展库。
This example creates a new class just for this one command. After you've done this more than once you'll probably see a pattern, and wrap it up in a generic utility class. See http://www.wpftutorial.net/delegatecommand.html for an example, or use any of the myriad of WPF extension libraries.
这篇关于如何使用程序创建的按钮在WPF MVVM中创建OnClick命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!