繁体   English   中英

ItemSource 外部的 Xamarin 表单绑定命令

[英]Xamarin Forms Bind command outside ItemSource

我有个问题。 我创建了这个 ListView:

<ListView ItemsSource="{Binding knownDeviceList}" SelectionMode="None" RowHeight="90" ItemTapped="device_Clicked">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Command="{Binding DeleteDevice}"
            CommandParameter="{Binding Id}"
            Text="Delete" IsDestructive="True" />
                </ViewCell.ContextActions>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ListView 绑定到一个包含对象的 List,但我需要将命令绑定到 ViewModel 根级别的 List 之外的 ICommand。 我该怎么做,因为现在当我尝试从列表中删除项目时不会触发 ICommand!

这是我的 ViewModel 中的命令:

public ICommand DeleteDevice
{
    get
    {
        return new Command<int>((x) => RemoveDevice_Handler(x));
    }
}

我究竟做错了什么?

您的MenuItem.BindingContext范围限于该单元格中的实际项目,而不是整个页面(或ListView )的视图模型。 您要么需要告诉绑定它需要查看其他位置,如下所示:

<ListView x:Name="MyListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Command="{Binding Path=BindingContext.DeleteDevice, Source={x:Reference MyListView}}}"/>
                </ViewCell.ContextActions>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

请注意,我删除了您在那里拥有的属性,只是为了明确我添加了哪些属性。 您可以保留它们,这只是为了便于阅读。

或者,您可以使用新的相对绑定 然后你可以像这样实现命令绑定:

Command="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModelClass}}, Path=DeleteDevice}"

您尝试从Command绑定的Context不是Page的,而是ItemSource ,这就是您可以简单地将Id绑定到CommandParameter

要解决此问题,您需要定位页面的BindingContext因为您的Command位于 ViewModel 根级别。 您可以通过向ListView添加x:Name属性并通过它定位正确的Context来实现它。

这里的修复:

<ListView x:Name="listView" ItemsSource="{Binding knownDeviceList}" SelectionMode="None" RowHeight="90" ItemTapped="device_Clicked">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
            <ViewCell>
                <ViewCell.ContextActions> 
                    <MenuItem Command = "{Binding BindingContext.DeleteDevice, Source={x:Reference listView}}"
                        CommandParameter="{Binding Id}"
                        Text="Delete" IsDestructive="True"  />
                </ViewCell.ContextActions>
            </ViewCell>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

希望它有帮助和快乐编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM