簡體   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