如何 - 正确绑定 ListView 内的按钮以查看模型 属性

How To - Properly Bind Button Inside of ListView to View Model Property

我似乎无法将命令连接到按钮。

假设我有以下内容:

MainPageViewModel.cs

public class MainPageViewModel : ViewModelBase
{
    private ICollection<MenuItem> _menuItems;

    public MainPageViewModel(INavigationService navigationService) : base(navigationService)
    {
        TestCommand = new DelegateCommand(TestCommandExecute);
        Title = "Menu";
    }

    public ICollection<MenuItem> MenuItems
    {
        get
        {
            return _menuItems;
        }

        private set
        {
            SetProperty(ref _menuItems, value, nameof(MenuItems));

            return;
        }
    }

    public DelegateCommand TestCommand
    {
        get;

        private set;
    }

    private void TestCommandExecute()
    {
        return;
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Menu.Views.MainPage" x:Name="Root" Title="{Binding Title}">
    <StackLayout>
        <Button Command="{Binding Mode=OneWay, Path=TestCommand}" Text="Test" />
        <ListView ItemsSource="{Binding Mode=OneWay, Path=MenuItems}" SeparatorVisibility="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <Button Command="{Binding Path=TestCommand, Source={x:Reference Name=Root}}" Text="{Binding Path=Title}" />
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

当我单击“测试”按钮时该命令将触发,但当我单击通过 ListView 生成的任何按钮时它不会触发。我已经通过在 TestCommandExecute 方法上放置一个断点来确认这一点。我没有看到生成任何错误。

这是将列表视图中的按钮连接到视图模型中的命令的正确方法吗?

我通过另一个 Stack Overflow 问题解决了这个问题...

绑定应该是...

<Button Command="{Binding Path=BindingContext.TestCommand, Source={x:Reference Name=Root}}" Text="{Binding Path=Title}" />

...而不是...

<Button Command="{Binding Path=TestCommand, Source={x:Reference Name=Root}}" Text="{Binding Path=Title}" />

注意添加的 BindingContext。

试试这个:

<Button Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainPage}}}"/>