【问题标题】:Binding ToolbarItem Click in Xamarin.Forms在 Xamarin.Forms 中绑定 ToolbarItem 单击
【发布时间】:2016-03-26 10:12:34
【问题描述】:

我正在尝试使用 Xamarin.Forms 构建我的第一个简单应用程序。

在这个应用程序中,我有一个带有 ListView 和工具栏的 ContentPage(在 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# 创建工具栏按钮(并向 ToolbarItem 构造函数添加 async () =&gt; { ... } 参数)
  3. 一个普通的(object sender, System.EventArgs e) =&gt; { ... } 事件监听器(通过带有.Clicked += 的代码)

【问题讨论】:

    标签: c# xamarin xamarin.forms


    【解决方案1】:

    我认为这是一个绑定上下文问题。如果您将命令放入单独的类(最好是 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();
    ...
    

    【讨论】:

    • 或者,您可以设置 this.BindingContext = this;
    • 在我的测试中没有按预期工作。你试过了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多