如何从集合中删除项目?

时间:2014-07-18 17:36:18

标签: c# wpf listview data-binding windows-runtime

所以即时创建一个允许用户制作习惯列表的应用程序。当我尝试养成新习惯时它工作正常。但我坚持如何删除它们。

这是绑定的XAML

<PivotItem  
            Header="HABIT LIST" 
            Margin="10,10,0,0">

            <ScrollViewer>

                <!--Habit item template-->
                <Grid Margin="0,0,10,0">
                    <Grid.Resources>
                        <DataTemplate x:Name="dataTemplate">

                            <Grid Margin="0,0,0,0"
                                  Holding="ListViewItem_Holding">

                                <!--ContextMenu-->
                                <FlyoutBase.AttachedFlyout>
                                    <MenuFlyout>
                                        <MenuFlyoutItem 
                                            x:Name="deletehabit"     
                                            Text="Delete"     
                                            Click="deletehabit_Click"       
                                            RequestedTheme="Dark"
                                            />
                                    </MenuFlyout>
                                </FlyoutBase.AttachedFlyout>

                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="105" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>

                                <!--ProgressBar-->
                                <StackPanel 
                                    Grid.Column="0" 
                                    CommonNavigationTransitionInfo.IsStaggerElement="True">

                                    <ProgressBar
                                        x:Name="habitbar"
                                        Grid.Column="0"
                                        Margin="0,105,-10,-105" 
                                        Value="{Binding Dates, Converter={StaticResource CompletedDatesToIntegerConverter}}"
                                        Maximum="21"
                                        Minimum="0" 
                                        Foreground="#FF32CE79"
                                        Width="100"  
                                        Height="50" 
                                        HorizontalAlignment="Stretch" 
                                        VerticalAlignment="Top" 
                                        RenderTransformOrigin="0,0" 
                                        Pivot.SlideInAnimationGroup="GroupOne" 
                                        FontFamily="Global User Interface"
                                        >
                                        <ProgressBar.RenderTransform>
                                            <CompositeTransform Rotation="270"/>
                                        </ProgressBar.RenderTransform>
                                    </ProgressBar>
                                </StackPanel>

                                <!--Details-->

                                <StackPanel 
                                    x:Name="habitdetail"
                                    Grid.Column="1"
                                    Margin="-30,0,0,0" >



                                    <TextBlock
                                        Text="{Binding Name}" 
                                        FontSize="24" 
                                        Foreground= "#FF3274CE"
                                        FontWeight="Thin"
                                        HorizontalAlignment="Left" 
                                        VerticalAlignment="Top" 
                                        FontFamily="Global User Interface"
                                        Pivot.SlideInAnimationGroup="GroupTwo"/>

                                    <TextBlock 
                                        Text="{Binding Description}"  
                                        FontSize="18"      
                                        FontWeight="Thin"   
                                        HorizontalAlignment="Left"    
                                        VerticalAlignment="Top" 
                                        FontFamily="Global User Interface" 
                                        LineHeight="10"
                                        Pivot.SlideInAnimationGroup="GroupTwo"/>

                                    <!--Button-->

                                    <Button 
                                        x:Name="CompletedButton"
                                        Content="!"
                                        Command="{Binding CompletedCommand}"
                                        CommandParameter="{Binding}"
                                        IsEnabled="{Binding Dates, Converter={StaticResource IsCompleteToBooleanConverter}}"
                                        HorizontalAlignment="Stretch" 
                                        VerticalAlignment="Stretch"
                                        Margin="0,5,0,0"
                                        Background="#FFCE3232" 
                                        Foreground="White"
                                        Height="21"
                                        BorderBrush="#FFCE3232" 
                                        FontFamily="Global User Interface" 
                                        ClickMode="Release"
                                        Pivot.SlideInAnimationGroup="GroupThree"
                                        Width="280"/>

                                </StackPanel>


                            </Grid>
                        </DataTemplate>
                    </Grid.Resources>

                    <ListView 
                        x:Name="habitlist" 
                        ItemsSource="{Binding}" 
                        ItemTemplate="{StaticResource dataTemplate}" 
                        Background="{x:Null}"
                        />

                </Grid>
            </ScrollViewer>

        </PivotItem>

这是删除我不知道输入内容的习惯的代码

    private void ListViewItem_Holding(object sender, HoldingRoutedEventArgs e)
    {
        FrameworkElement senderElement = sender as FrameworkElement;
        FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);

        flyoutBase.ShowAt(senderElement);
    }

    private void deletehabit_Click(object sender, RoutedEventArgs e)
    {
       //TODO

    }

并且继承了数据模型

public class Habit : INotifyPropertyChanged

{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ObservableCollection<DateTime> Dates { get; set; }

    [IgnoreDataMember]
    public ICommand CompletedCommand { get; set; }

    public Habit()
    {
        CompletedCommand = new CompletedButtonClick();
        Dates = new ObservableCollection<DateTime>(); 
    }

    public void AddDate()
    {
        Dates.Add(DateTime.Today);
        NotifyPropertyChanged("Dates");        
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class DataSource
{
    private ObservableCollection<Habit> _habits;

    const string fileName = "habits.json";

    public DataSource()
    {
        _habits = new ObservableCollection<Habit>();
    }

    public async Task<ObservableCollection<Habit>> GetHabits()
    {
        await ensureDataLoaded();
        return _habits;
    }

    private async Task ensureDataLoaded()
    {
      if (_habits.Count == 0)
          await getHabitDataAsync();

      return;
    }

    private async Task getHabitDataAsync()
    {
      if (_habits.Count != 0)
          return;

      var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<Habit>));

      try
      {
          // Add a using System.IO;
          using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName))
          {
              _habits = (ObservableCollection<Habit>)jsonSerializer.ReadObject(stream);
          }
      }
      catch
      {
          _habits = new ObservableCollection<Habit>();
      }
    }

    public async void AddHabit(string name, string description)
    {
        var habit = new Habit();
        habit.Name = name;
        habit.Description = description;
        habit.Dates = new ObservableCollection<DateTime>();

        _habits.Add(habit);
        await saveHabitDataAsync();
    }

    private async Task saveHabitDataAsync()
    {
        var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<Habit>));
        using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName,
            CreationCollisionOption.ReplaceExisting))
        {
            jsonSerializer.WriteObject(stream, _habits);
        }
    }

    public async void CompleteHabitToday(Habit habit)
    {
        int index = _habits.IndexOf(habit);
        _habits[index].AddDate();
        await saveHabitDataAsync();
    }
}

我非常喜欢编程 感谢

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,请拨打

NameOfCollectionGoesHere.Remove()

方法

您还可以使用

清除整个集合
.Clear()

这就是你要求的吗?