2014-07-18 3 views
0

그래서 사용자가 습관 목록을 만들 수있는 앱을 만듭니다. 새로운 습관을 만들려고 할 때 잘 작동합니다. 그러나 나는 그들을 삭제하는 방법에 머물렀다. 컬렉션에서 항목을 삭제하는 방법은 무엇입니까?

이 코드는 내가

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 

    } 

을 입력 해야할지하지 않는 습관을 heres 데이터 모델을 삭제하기위한 뒤에있는 바인딩

<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> 

에 대한 XAML입니다

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(); 
    } 
} 

메신저 매우 새로 프로그래밍 감사합니다.

내가 제대로 질문을 이해한다면 16,

답변

0

, 단지

NameOfCollectionGoesHere.Remove() 

메서드를 호출합니다.

또한

.Clear() 

로 전체 컬렉션을 지울 수는 당신이 요구하는 무엇인가요?

+0

내 컬렉션 이름이 현재 컨텍스트에 존재하지 않는다고합니다. 나는 이미 Habit21.DataModel을 사용했다. 뿐만 아니라 참조. 그리고 내가 무엇을 입력하는지 heres. _habits.Remove(); – user3853952

관련 문제