2016-03-26 52 views
2

我想用Xamarin.Forms構建我的第一個簡單的應用程序。綁定ToolbarItem點擊Xamarin.Forms

在這個應用程序中,我有一個ListPage和一個工具欄(在一個NavigationPage中)。

工具欄有一個ToolbarItem,它應該在單擊時運行一個方法。即使我已經搜索到Google瘦,我根本無法得到它的工作...

有人可以告訴我我失蹤了嗎?

XAML:

<?xml version="1.0" encoding="UTF-8"?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:constants="clr-namespace:FlashCards;assembly=FlashCards" 
x:Class="FlashCards.SetsPage" 
Title="Card Sets"> 
    <ContentPage.ToolbarItems> 
      <ToolbarItem Name="Add" Icon="Icon-Button-Add.png" Command="{Binding CreateCommand}"></ToolbarItem> 
    </ContentPage.ToolbarItems> 
    <ListView x:Name="CardSetView"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
     <TextCell Text="{Binding Title}" /> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
    </ListView> 
</ContentPage> 

代碼隱藏:

//... 
public partial class SetsPage : ContentPage 
    { 
     ObservableCollection<CardSet> sets = new ObservableCollection<CardSet>(); 

     public Command CreateCommand { get; private set; } 

     public SetsPage() { 

      InitializeComponent(); 

      sets.Add(new CardSet{ Title = "Test 1" }); 
      sets.Add(new CardSet{ Title = "Test 2" }); 
      sets.Add(new CardSet{ Title = "Test 3" }); 

      CardSetView.ItemsSource = sets; 

      this.CreateCommand = new Command(async (sender) => 
       { 
        Debug.WriteLine("Hello"); 
       }); 

     } 
    } 
//... 

我已經試過:

  1. 你看到上面
  2. 創建工具欄按鈕只有通過什麼C#(並添加一個async() => { ... }參數的構造函數ToolbarItem)
  3. 定期醇」 (object sender, System.EventArgs e) => { ... }事件偵聽器(通過代碼.Clicked +=

回答

0

我認爲這是一個綁定上下文問題。如果你有命令到一個單獨的類(理想的是視圖模型),並以此作爲約束背景下爲您的網頁,那麼就應該按預期工作

public class MyVm { 
    public MyVm() { 
     this.CreateCommand = new Command((sender) => 
     { 
      Debug.WriteLine("Hello"); 
     }); 
    } 

    public ICommand CreateCommand { get; private set; } 
} 

... 

public SetsPage() { 
     var vm = new MyVm(); 
     this.BindingContext = vm; 

     InitializeComponent(); 
... 
+0

或者,你可以只設置this.BindingContext =這一點; – Jason

+0

在我的測試中無法按預期工作。你試過了嗎? –