[英]Binding ToolbarItem Click in Xamarin.Forms
我正在尝试使用 Xamarin.Forms 构建我的第一个简单应用程序。
在这个应用程序中,我有一个带有 ListView 和工具栏的 ContentPage(在 NavigationPage 内)。
Toolbar 有一个 ToolbarItem,点击时应该运行一个方法。 即使我已经在谷歌上搜索过瘦身,我也无法让它工作......
谁能告诉我我错过了什么?
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");
});
}
}
//...
我试过:
async () => { ... }
参数)(object sender, System.EventArgs e) => { ... }
事件监听器(通过带有.Clicked +=
代码)我认为这是一个绑定上下文问题。 如果您将命令放入一个单独的类(最好是 ViewModel)并将其用作页面的绑定上下文,那么它应该可以按预期工作
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();
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.