Xamarin Forms ListView item Command未绑定到VM中的ICommand

a0x5cqrl  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(127)

我有一个ContentPage,它有一个ListView。在ListView的DataTemplate中有一个TextCell,它保存了一个字符串值,我已经绑定在相应的ViewModel中。我将所述TextCell的命令绑定到我的ViewModel中的ICommand。当我加载一个模拟器,并单击一个单元格项时,什么都没有发生。我没有命中绑定的ICommand上的ViewModel中的断点。我是否遗漏了什么?免责声明:我已经离开Xamarin一段时间了。
浏览次数:

<ListView ItemsSource="{Binding matchupList}" >
    
    <ListView.ItemTemplate>
        <DataTemplate>
         <TextCell Text="{Binding matchup}" Detail="{Binding matchupDescription}"  Command="{Binding SelectedCommand}" /> 
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

代码隐藏:

public partial class GamesByDate : ContentPage
{   
    public GamesByDate ()
    {
        InitializeComponent ();
        BindingContext = new GamesByDateViewModel(Navigation);
    }
}

视图模型:

public ICommand SelectedCommand => new Command(async () => await GotoPage2());
public async Task GotoPage2()
    {
        try
        {
           //DoSomething

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

    }

我的使命是点击ListView中的一个项目,触发ICommand,调用VM中的另一个方法。谢谢!

dwbf0jvd

dwbf0jvd1#

正如Jason所说,你可以使用Relative bindings。试试下面的代码:

<DataTemplate>
 <TextCell Text="{Binding matchup}" Detail="{Binding matchupDescription}"  Command="{Binding Source={RelativeSource AncestorType={x:Type local:MainPageViewModel}}, Path=SelectedCommand}" /> 
</DataTemplate>

希望能成功。

相关问题