Xamarin.FormでListViewを使ってアイテムの追加、削除を行う以下のようなプログラムを書きました。
xaml
1MainPage.xaml 2 3<?xml version="1.0" encoding="utf-8" ?> 4<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 5 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 6 x:Class="test.Views.MainPage" 7 x:Name="root" 8 Title="{Binding Title}"> 9 <StackLayout> 10 <ListView ItemsSource="{Binding List}"> 11 <ListView.ItemTemplate> 12 <DataTemplate> 13 <ViewCell> 14 <ViewCell.ContextActions> 15 <MenuItem Text="削除" Command="{Binding BindingContext.DeleteCommand, Source={x:Reference root}}" 16 CommandParameter="{Binding}"/> 17 </ViewCell.ContextActions> 18 <StackLayout> 19 <Label Text="{Binding Guid}" BackgroundColor="Black" TextColor="White"/> 20 </StackLayout> 21 </ViewCell> 22 </DataTemplate> 23 </ListView.ItemTemplate> 24 </ListView> 25 <Button Text="Add" Command="{Binding AddCommand}"/> 26 </StackLayout> 27</ContentPage>
C#
1 2MainPage.xaml.cs 3 4using System; 5using Xamarin.Forms; 6 7namespace test.Views 8{ 9 public partial class MainPage : ContentPage 10 { 11 public MainPage() 12 { 13 InitializeComponent(); 14 } 15 } 16}
C#
1MainPageViewModel.cs 2 3using Prism.Mvvm; 4using Prism.Navigation; 5using System; 6using System.Collections.ObjectModel; 7using Xamarin.Forms; 8 9namespace test.ViewModels 10{ 11 public class MainPageViewModel : ViewModelBase 12 { 13 14 public class Item : BindableBase 15 { 16 private string guid; 17 18 public string Guid 19 { 20 get { return guid; } 21 set { SetProperty(ref guid, value); } 22 } 23 24 public Item(string id) 25 { 26 Guid = id; 27 } 28 } 29 30 public ObservableCollection<Item> List { get; set; } = new ObservableCollection<Item>(); 31 32 public Command<Item> DeleteCommand { get; } 33 public Command AddCommand { get; } 34 35 public MainPageViewModel(INavigationService navigationService, DropBoxModel dropBoxModel) 36 : base(navigationService) 37 { 38 39 AddCommand = new Command(_ => List.Add(new Item(Guid.NewGuid().ToString()))); 40 DeleteCommand = new Command<Item>(hoge => List.Remove(hoge as Item)); 41 } 42 } 43}
Androidでは問題ないのですが、UWPで項目を削除したあとに追加をすると、その項目を削除できないことに気づきました。
デバッガを使って変数を確認したところ、追加した項目のMenuItemのBindingContextが何故か削除された項目のものになっていることがわかりました。
どうすればMenuItemのBindingContextが正しく設定されるのでしょうか・・・?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。