如标题所言,是做删除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 }
代码都已附上,就这样结束吧,如若有问题可以联系,qq:1358338055
时间: 2024-10-07 18:22:25