如標題所言,是做刪除ListView綁定項的功能的;鑒於這個功能當時確實花費了很多時間,並且網上也找不到刪除所需的案例,所以,我就做了一份案例,僅供各位前輩和同行進行參考,如有不當之處,還望指點,我將再接再勵,下面進入正題:
按照需求我們是需要實現的功能:點擊刪除的時候,把整個Items給移除,最初用listview.Items.RemoveAt(Listview.SelectedIndex)這樣的方式來刪除,調試的時候報“災難性......”的錯誤,無奈我只能嘗試listview.Items.Remove(Listview.SelectedItems)以及listview.Items.Remove(Listview.SelectedItem[0])等等方式,都不行,不是報災難性的錯誤,就是沒效果;當時頭真的好疼,上網找資料,沒有想要的,只能去向群裡問大神,大神的想法及編碼水平確實讓我望塵莫及;但是,即便大神寫的代碼,也不能實現我想要的功能,只好繼續想辦法,借鑒c#的其它辦法,如果是開發uwp的就知道,寫uwp的C#和微軟之前的C#有些許的不同,所以我只能繼續嘗試,後來終於想到,我直接操作綁定的通知列表不就可以了嗎,操作完畢再重新綁定一次就好了啊,
於是,功能就實現了,下面展示詳細代碼:
1 <ListView x:Name="listView" Grid.Row="2" 2 HorizontalAlignment="Center" 3 Margin="0" VerticalAlignment="Center"> 4 <ListView.Resources> 5 <Style TargetType="ListViewItem"> 6 <Setter Property="Padding" Value="0"></Setter> 7 <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> 8 <Setter Property="Template"> 9 <Setter.Value> 10 <ControlTemplate TargetType="ListViewItem"> 11 <Grid Background="{TemplateBinding Background}"> 12 <ContentPresenter 13 Content="{TemplateBinding Content}" 14 Margin="{TemplateBinding Padding}" /> 15 </Grid> 16 </ControlTemplate> 17 </Setter.Value> 18 </Setter> 19 </Style> 20 </ListView.Resources> 21 <ListView.ItemTemplate> 22 <DataTemplate> 23 <RelativePanel MinWidth="330" 24 MinHeight="50" 25 CornerRadius="3" 26 Margin="5" 27 BorderBrush="Green" 28 BorderThickness="1"> 29 <TextBlock Name="tbName" RelativePanel.AlignLeftWithPanel="True" 30 Text="{Binding name}"></TextBlock> 31 <TextBlock RelativePanel.Below="tbName" Margin="0,5,0,0" 32 Text="{Binding sex}"></TextBlock> 33 <TextBlock Name="tbDelItem" VerticalAlignment="Center" RelativePanel.AlignRightWithPanel="True" 34 FontSize="18" Text="" FontFamily="{StaticResource SymbolThemeFontFamily}" 35 Foreground="Red" Tapped="tbDelItem_Tapped" 36 RelativePanel.AlignVerticalCenterWithPanel="True"></TextBlock> 37 </RelativePanel> 38 </DataTemplate> 39 </ListView.ItemTemplate> 40 </ListView>
後台的也加上來:
1 public sealed partial class MainPage : Page 2 { 3 ObservableCollection<Info> oc { get; set; } = new ObservableCollection<Info>(); 4 public MainPage() 5 { 6 this.InitializeComponent(); 7 } 8 9 protected override void OnNavigatedTo(NavigationEventArgs e) 10 { 11 12 13 this.DataContext = this; 14 for (int i = 0; i < 10; i++) 15 { 16 oc.Add(new Info() { name="張三"+i, sex="男"+i}); 17 } 18 listView.ItemsSource = oc; 19 } 20 21 private void tbDelItem_Tapped(object sender, TappedRoutedEventArgs e) 22 { 23 //當我click目標對象的時候,就已經選中了對象所在的整個綁定對象, 24 //然後,移除通知列表ObservableCollection<Info>裡面對應的對象 25 Info fn = listView.SelectedItem as Info; 26 oc.Remove(fn); 27 listView.ItemsSource = oc; 28 } 29 } 30 31 public class Info 32 { 33 public string name { get; set; } 34 public string sex { get; set; } 35 public string hobby { get; set; } 36 37 }View Code
代碼都已附上,就這樣結束吧,如若有問題可以聯系,qq:1358338055