CommandParameter绑定未更新

时间:2017-08-11 07:56:04

标签: c# xaml xamarin xamarin.forms

以下代码显示 ListView ,其中ItemSource是 PageModel ObservableCollection 。它的项目有ContextActions来编辑或删除它们。

<!--BindingContext = new PageModel()-->
<ListView x:Name="itemList" ItemSource="{Binding Items}">
    <ListView.ItemTamplate>
        <DataTemplate>
            <TextCell Text="{Binding Title} Detail="{Binding Index, StringFormat='{0}'}">
                <TextCell.ContextActions>
                    <MenuItem
                        Command="{Binding Source={x:Reference itemList}, Path=BindingContext.EditCommand}"
                        CommandParameter="{Binding .}
                        Text="Edit" />
                    <MenuItem
                        Command="{Binding Source={x:Reference itemList}, Path=BindingContext.DeleteCommand}"
                        CommandParameter="{Binding .}
                        IsDestructive="True"
                        Text="Delete" />
                </TextCell.ContextActions>
            </TextCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
class PageModel {
    public ObservableCollection<Item> Items { get; }
    public ICommand EditCommand { get; }
    public ICommand DeleteCommand { get; }

    public PageModel() {
        this.EditCommand = new Command<Item>(EditItem);
        this.DeleteCommand = new Command<Item>(DeleteItem);

        this.Items = new ObservableCollection {
            new Item(0, "Item 1"),
            new Item(1, "Item 2"),
            new Item(2, "Item 3")
        }
    }

    private void EditItem(Item item) {
        this.Items.RemoveAt(item.Index);
        this.Items.Insert(item.Index, new Item(item.Index. "Changed Title"));
    }
    private void DeleteItem(Item item) {
        this.Items.Remove(item);
    }
}

class Item {
    public int Index { get; set; }
    public string Title { get; set; }
    // Constructor ...
}

问题是,在我编辑项目之后,所有内容都会更新 - Items集合,UI,... - 除了MenuItems的CommandParameter。当我第二次单击Edit-Button时,EditItem方法的参数是应该删除的旧Item。这也阻止我删除该项目,因为该集合不再存储旧项目的旧项目。

如何解决这个问题?可以以某种方式触发CommandParameter的更新吗?为什么会发生这种情况呢? Aren用相关的ListViewItems呈现的MenuItem?

0 个答案:

没有答案