locked
How can I substract value from a total of a ViewList when I use Command? RRS feed

  • Question

  • Hi,

    I have a ListView( with 2 columns(Description and Calories) and a Button Delete(It removes items from ViewList)),
    a TextBlock with total of column Calories.
    Input elements: 2 TextBox( txtDesc and txtCal), 2 buttoms( Add and Clear)

    Data are storeded in sqlite database.

    I am able to add Items to the ListView and database and show in the total in the TextBlock txtTotal.
    When I hit Delete button of the ListView I am able to remove item from ListView and database but
    I don't know how to update the total.


          <StackPanel x:Name="panelMain"  HorizontalAlignment="Left"  Orientation="Vertical" Grid.Row="1"
                                             VerticalAlignment="Top" Width="500" >


                <StackPanel x:Name="panelComboDisplayed" Orientation="Vertical" Width="500"  HorizontalAlignment="Left" >
                    <Border BorderThickness="1" Background="Navy" >
                        <StackPanel  Width="500" Height="30" Orientation="Horizontal" >
                            <TextBlock TextWrapping="Wrap"  FontSize="22" Text="Food Descripton" Foreground="#FF91D6F5" TextAlignment="Center" 
                                      Width="400" FontWeight="Bold" />
                            <TextBlock TextWrapping="Wrap"  FontSize="22" Text="Calories" Foreground="#FF91D6F5" TextAlignment="Center" 
                                      Width="100" FontWeight="Bold" />

                        </StackPanel>
                    </Border>

                    <StackPanel x:Name="panelDescVal" Orientation="Horizontal"  HorizontalAlignment="Left" Width="500" Visibility="Collapsed" >
                        <TextBlock x:Name="txtDescErr" TextWrapping="Wrap"  FontSize="22" Text=""  Foreground="Red" />

                        <TextBlock x:Name="txtDescVal" Text="" Foreground="Red" FontSize="22" TextAlignment="Left" VerticalAlignment="Bottom" />
                    </StackPanel>
                    <StackPanel x:Name="panelCalVal" Orientation="Horizontal"  HorizontalAlignment="Left" Width="500" Visibility="Collapsed" >
                        <TextBlock x:Name="txtCalErr" TextWrapping="Wrap"  FontSize="22" Text=""  Foreground="Red" />

                        <TextBlock x:Name="txtCalVal" Text="" Foreground="Red" FontSize="22" TextAlignment="Left" VerticalAlignment="Bottom" />
                    </StackPanel>

                    <StackPanel x:Name="panelInput" Orientation="Horizontal" Width="500"  HorizontalAlignment="Right"  >
                        <TextBox x:Name="txtDesc" TextWrapping="Wrap" FontSize="24" Text="" Width="398" HorizontalContentAlignment="Left" HorizontalAlignment="Left"
                                 FontWeight="Bold"  TextChanged="txtDesc_TextChanged" />
                        <TextBlock TextWrapping="Wrap"  FontSize="22" Text="" Foreground="#FF91D6F5" TextAlignment="Center" 
                                      Width="2" FontWeight="Bold" />

                        <TextBox x:Name="txtCal" TextWrapping="Wrap" FontSize="24" Text="" Width="100" HorizontalAlignment="Right"
                                 TextAlignment="Center" TextChanged="txtCal_TextChanged"
                                 HorizontalContentAlignment="Right"
                                 FontWeight="Bold" />


                    </StackPanel>

                    <StackPanel x:Name="panelButtons" Orientation="Horizontal" Width="500"  HorizontalAlignment="Left" >
                        <Button Content="Add Food" Height="50" Width="250" FontSize="22"
                          HorizontalAlignment="Center"
                          x:Name="buttonAddFood"
                          Foreground="OrangeRed"
                          BorderBrush="OrangeRed" Click="buttonAddFood_Click"  />
                        <Button Content="Clear Food" Height="50" Width="250" FontSize="22"
                          HorizontalAlignment="Center"
                          x:Name="buttonClearFood"
                          Foreground="OrangeRed"
                          BorderBrush="OrangeRed" Click="buttonClearFood_Click"  />
                    </StackPanel>

                    <StackPanel x:Name="panelTotal" Orientation="Horizontal" Width="500"  HorizontalAlignment="Left" >
                        <TextBlock x:Name="txtTotalFoodT" TextWrapping="Wrap" FontSize="20" Text="Total Food = " Foreground="Yellow"/>
                        <TextBlock x:Name="txtTotalFood" TextWrapping="Wrap" FontSize="20" Text="0"  Foreground="Yellow"/>
                        <TextBlock x:Name="txtTotalFoodTT" TextWrapping="Wrap" FontSize="20" Text=" Calories "  Foreground="Yellow"/>
                    </StackPanel>
                </StackPanel>


                <StackPanel x:Name="panelListView" Orientation="Vertical" Width="500"  HorizontalAlignment="Left" >

                    <ListView Name="FoodDListView"
                              Visibility="Visible"
                              AutomationProperties.AutomationId="FoodDListView"
                              AutomationProperties.Name="FoodD Group"    
                              ScrollViewer.VerticalScrollBarVisibility="Visible"
                              ScrollViewer.VerticalScrollMode="Enabled"
                              BorderThickness="1"
                              BorderBrush="Yellow"
                              Background="Navy"
                              ItemsSource="{Binding FoodDs}"
                              >
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <Grid Width="500" Height="40">
                                    <StackPanel Orientation="Horizontal" Width="500">

                                        <StackPanel Orientation="Horizontal" Visibility="Collapsed">
                                            <TextBlock Text="Id:"  Margin="0,0,5,0"/>
                                            <TextBlock Text="{Binding _id}" />
                                        </StackPanel>

                                        <StackPanel Orientation="Horizontal">

                                            <TextBlock Text="{Binding description}"  Margin="0,10,0,0"/>
                                            <TextBlock Text=" = "  Margin="0,10,0,0" Visibility="Visible"/>
                                            <TextBlock Text="{Binding calories}" Margin="0,10,0,0"/>
                                            <TextBlock Text=" Calories:" Margin="0,10,0,0"/>
                                        </StackPanel>


                                    </StackPanel>
                                    <StackPanel Orientation="Vertical" Margin="370,0,0,0">
                                        <Button Content="Delete" Margin="0,0,0,0"  Command="{Binding DataContext.DeleteCommand, ElementName=FoodDListView}" CommandParameter="{Binding _id}"/>
                                    </StackPanel>

                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                        <ListView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapGrid MaximumRowsOrColumns="8" VerticalChildrenAlignment="Top"
           HorizontalChildrenAlignment="Left" Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ListView.ItemsPanel>
                    </ListView>

                </StackPanel>

            </StackPanel>


    ADRIAN DIBU

    Sunday, January 5, 2014 3:27 PM

Answers

  • Hi,

    I tried:

      protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                  FoodDListView.DataContextChanged += FoodDListView_DataContextChanged;

             navigationHelper.OnNavigatedTo(e);
            }

     private void FoodDListView_DataContextChanged(object sender, NotifyCollectionChangedEventArgs e)
            //    private void FoodDListView_ContainerContentChanging(object sender, NotifyCollectionChangedEventArgs e)
            //  private void FoodDListView_SelectionChanged(object sender, (object sender, NotifyCollectionChangedEventArgs e) e)
            {
                //The projects ListView has been changed
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        //MessageBox.Show("An Item Has Been Added To The ListView!");
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        // MessageBox.Show("The ListView Has Been Cleared!");
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        txtTotalFood.Text = App.pFood;
                        break;
                }
            }

    I had the error
    No overload for 'FoodDListView_DataContextChanged' matches delegate 'Windows.Foundation.TypedEventHandler<Windows.UI.Xaml.FrameworkElement,Windows.UI.Xaml.DataContextChangedEventArgs>'

    Thanks


    ADRIAN DIBU

    • Marked as answer by adibu Tuesday, January 14, 2014 3:07 AM
    Tuesday, January 7, 2014 5:36 PM

All replies

  • Hi,

    The rest of code.


     public class FoodDViewModel : INotifyPropertyChanged
        {
            #region Fields and Properties
            private Windows.Storage.ApplicationDataContainer roamingSettings =
                 Windows.Storage.ApplicationData.Current.RoamingSettings;

            // This property will be bound to GridView's ItemsDataSource property for providing data
            private ObservableCollection<FoodD> foodDs;

            // This property will be bound to button's Command property for deleting item
            public IDelegateCommand DeleteCommand { protected set; get; }

            public ObservableCollection<FoodD> FoodDs
            {
                get
                {
                    return foodDs;
                }
                set
                {
                    if (foodDs != value)
                    {
                        foodDs = value;
                        OnPropertyChanged("FoodDs");
                    }
                }
            }

            #endregion

            #region Constructor


            public FoodDViewModel()
            {
                // create a DeleteCommand instance
                this.DeleteCommand = new DelegateCommand(ExecuteDeleteCommand);

                // Get data source
               FoodDs = InitializeSampleDataS.GetData();
            //   FoodDs = InitializeSampleDataS.GetDataS(1, "Burger King", "Salad", "Cucomber", "100", "120g");
            }
            #endregion


            #region Execute and CanExecute methods
            void ExecuteDeleteCommand(object param)
            {
                int cal = 0;
                int calApp = 0;
                int calTot = 0;

                int id = (Int32)param;
                  FoodD cus = GetFoodDById(id);
                   if (cus != null)
                   {
                    
                       //Remove Item
                     FoodDs.Remove(cus);

                  // Calculate new total
                     cal = System.Convert.ToInt32(cus.calories);
                     calApp = System.Convert.ToInt32(App.pFood);
                     calTot = calApp - cal;
                    
                     App.pFood = calTot.ToString();
                     App.myValueFood = App.pFood;
                     roamingSettings.Values["MyValueFood"] = App.myValueFood;

                       //  Delete record by id
                     FoodMViewModel foodMViewModel = new FoodMViewModel();
                     string result = foodMViewModel.DeleteFoodM(id);
                 //    System.Diagnostics.Debug.WriteLine(" Delete FoodM result: " + result);
              
                 }
            }

            #endregion

            // Get the deleting item by Id property
            private FoodD GetFoodDById(int id)
            {
                  return FoodDs.First(x => x._id== id);
            }


            #region INotifyPropertyChanged

            public event PropertyChangedEventHandler PropertyChanged;

            private void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
            #endregion
        }
     private void buttonAddFood_Click(object sender, RoutedEventArgs e)
            {

             // Add Selected Food to FoodM

                foodMViewModel = new FoodMViewModel();

                FoodM foodM1 = new FoodM();

                foodM1.Description = strDesc;  // txtDesc.Text;//txtDescription.Text.Substring(0, txtDescription.Text.IndexOf("=")  );
                foodM1.Calories = strCal;//txtCal.Text; //txtCalories.Text;

                string result1 = foodMViewModel.AddFoodMDupl(foodM1);

                 System.Diagnostics.Debug.WriteLine("result1 : " + result1);

                 foodDViewModel = new FoodDViewModel();

                 FoodDListView.DataContext = foodDViewModel;  // Excelent see ListView

                 FoodMsViewModel foodMsViewModel1 = new FoodMsViewModel();

                 ObservableCollection<FoodMViewModel> foodMViewModel1 = new ObservableCollection<FoodMViewModel>();
                foodMViewModel1 =  foodMsViewModel1.GetFoodMs();
              
                List<double> listPayJD1 = new List<double>();
                if (foodMViewModel1.Count > 0)
                {
                    foreach (var prime11 in foodMViewModel1) // Loop through List with foreach
                    {
                        listPayJD1.Add(System.Convert.ToDouble(prime11.Calories));
                    }
                    double sum31 = 0.0;
                    sum31 = listPayJD1.Sum();

                    txtTotalFood.Text = sum31.ToString();

                    App.pFood = sum31.ToString(); // (Convert.ToInt32(foodOS.Substring(foodOS.IndexOf("=") + 1, foodOS.Length - 1 - foodOS.IndexOf("=")))).ToString();
                    App.myValueFood = App.pFood;
                    roamingSettings.Values["MyValueFood"] = App.myValueFood;
                }
            }
            private void buttonClearFood_Click(object sender, RoutedEventArgs e)
            {
                FoodMViewModel foodMViewModel3 = new FoodMViewModel();
                string result = foodMViewModel3.DeleteAllFoodM();
                foodDViewModel = new FoodDViewModel();

                FoodDListView.DataContext = foodDViewModel;  // Excelent see ListView

                App.pFood = "0";
                App.myValueFood = App.pFood;
                roamingSettings.Values["MyValueFood"] = App.myValueFood;
                txtTotalFood.Text = "0";

            }


    ADRIAN DIBU

    Sunday, January 5, 2014 3:28 PM
  • Hi adibu,

    I just wondering how to implement the value while adding an item to the list. Subtract should be as same as subjoin, the only difference is one for plus and another one for minus. Here you use

    private void buttonAddFood_Click(object sender, RoutedEventArgs e)

    but why not have a:

    private void buttonDeleteFood_Click(object sender, RoutedEventArgs e)

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Tuesday, January 7, 2014 2:22 AM
    Moderator
  • Hi,

    Thanks for answer.

    The Delete Button must belong to the FoodDViewModel

    (I used command to delete items and it works perfect)

    not to the FoodNew Page.

    I don't know how to use NotifyCollectionChangedEventArgs

    to detect after Command was executed that Collection was changed

    and to update the txrTotal text block belonging to the FoodNew Page.

    Thanks


    ADRIAN DIBU

    Tuesday, January 7, 2014 2:17 PM
  • Hi,

    I tried:

      protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                  FoodDListView.DataContextChanged += FoodDListView_DataContextChanged;

             navigationHelper.OnNavigatedTo(e);
            }

     private void FoodDListView_DataContextChanged(object sender, NotifyCollectionChangedEventArgs e)
            //    private void FoodDListView_ContainerContentChanging(object sender, NotifyCollectionChangedEventArgs e)
            //  private void FoodDListView_SelectionChanged(object sender, (object sender, NotifyCollectionChangedEventArgs e) e)
            {
                //The projects ListView has been changed
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        //MessageBox.Show("An Item Has Been Added To The ListView!");
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        // MessageBox.Show("The ListView Has Been Cleared!");
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        txtTotalFood.Text = App.pFood;
                        break;
                }
            }

    I had the error
    No overload for 'FoodDListView_DataContextChanged' matches delegate 'Windows.Foundation.TypedEventHandler<Windows.UI.Xaml.FrameworkElement,Windows.UI.Xaml.DataContextChangedEventArgs>'

    Thanks


    ADRIAN DIBU

    • Marked as answer by adibu Tuesday, January 14, 2014 3:07 AM
    Tuesday, January 7, 2014 5:36 PM