2016-03-26 49 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

在我的测试中无法按预期工作。你试过了吗? –