[英]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.