[英]Xamarin forms, how can my command from my viewmodel reach/connect with an existing button?
这是我拥有命令的viewmodel,它可以更改int的值。 我想将此命令绑定到一个按钮。
public SharedViewModel()
{
ClickCommand = new Command (() => CurrentValue = CurrentValue + 1);
}
public ICommand ClickCommand
{
get { return clickCommand; }
set
{
clickCommand = value;
OnPropertyChanged("ClickCommand");
}
}
这是我的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?
}
从后面的代码中,您可以执行此操作
myButton.Command = ourSharedView.ClickCommand;
您应该删除Button的Click处理程序-如果您使用Command,则不需要它
首先,从View(Page)创建一个View模型不是一个好主意。 虚拟机存在后应创建页面并使用它的数据。
至于您的问题,假设您具有具有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
}
}
带注释的行与私密行的功能相同,请使用其中之一。
PS忘记提及要正常工作,必须将页面的BindingContext属性设置为此页面的视图模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.