[英]Xamarin forms, how can my command from my viewmodel reach/connect with an existing button?
This is my viewmodel where I have the command, that changes the value of an int. 这是我拥有命令的viewmodel,它可以更改int的值。 I want to bind this command to a Button.
我想将此命令绑定到一个按钮。
public SharedViewModel()
{
ClickCommand = new Command (() => CurrentValue = CurrentValue + 1);
}
public ICommand ClickCommand
{
get { return clickCommand; }
set
{
clickCommand = value;
OnPropertyChanged("ClickCommand");
}
}
And this is my ContentPage
where I have a button named click1
: 这是我的
ContentPage
,其中有一个名为click1
的按钮:
public MenuPage ()
{
var ourSharedView = new SharedViewModel ();
ourSharedView.ClickCommand; //and this is the command, I have no idea how I should connect this with my existing button below though. This
}
void click1 (object s, EventArgs a)
{
// how can I connect this clickbutton to my command?
}
From the code behind, you can do this 从后面的代码中,您可以执行此操作
myButton.Command = ourSharedView.ClickCommand;
you should remove the Button's Click handler - you do not need it if you are using a Command 您应该删除Button的Click处理程序-如果您使用Command,则不需要它
First of all creating a View Model from the View(Page) is not a good idea. 首先,从View(Page)创建一个View模型不是一个好主意。 Page should be created after VM is exist and use it's data.
虚拟机存在后应创建页面并使用它的数据。
I recomend you to read the Data binding basics , MVVM binding . 我建议您阅读数据绑定基础知识 MVVM绑定 。
As for your question assume you have View Model with ICommand property, set binding of the button command in page to it: 至于您的问题,假设您具有具有ICommand属性的View Model,则将页面中的button命令设置为其绑定:
public class CustomPage : ContentPage
{
private Button btn {get;set;}
public CustomPage()
{
if(btn == null)
btn = createButtonFunction();
btn.SetBinding<ViewModelClassName>(Button.CommandProperty, vm => vm.CommandFromViewModel)
//btn.SetBinding(Button.CommandProperty, "CommandFromViewModel")//other way to set binding
}
}
Commented line does same work as privious, use one of them. 带注释的行与私密行的功能相同,请使用其中之一。
PS Forget to mention that to work propertly BindingContext property of page has to be set to the View Model of this page. PS忘记提及要正常工作,必须将页面的BindingContext属性设置为此页面的视图模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.