locked
Not able to get the text property of custom stepper used in the xaml file to its cs file in xamarin RRS feed

  • Question

  • User392765 posted

    Here group binding is done and the products are listed under the corresponding dealers. I want to multiply the price and quantity of each products under one dealer and store it in a List_model-OrderModel when the View Order button is clicked. I am not able to access the quantity value in the custom stepper text. I tried var qty = stepper.Text. but the name stepper is not coming. CustomStepper and Stepper is coming the dropdown.

    This is my custom stepper:

    /*Created this class to make a custon stepper to add quantity */ public class CustomStepper : StackLayout { Button PlusBtn; Button MinusBtn; Label QtyLbl;

    public static readonly BindableProperty TextProperty =
      BindableProperty.Create(
         propertyName: "Text",
          returnType: typeof(int),
          declaringType: typeof(CustomStepper),
          defaultValue: 0,
          defaultBindingMode: BindingMode.TwoWay);
    
    public int Text
    {
        get { return (int)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    
    public CustomStepper()
    {
        PlusBtn = new Button { Text = "+", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};
        MinusBtn = new Button { Text = "-", WidthRequest = 23, HeightRequest = 25, FontSize = 11, BackgroundColor = Color.LightGray, Padding = 0};
    
        Orientation = StackOrientation.Horizontal;
        PlusBtn.Clicked += PlusBtn_Clicked;
        MinusBtn.Clicked += MinusBtn_Clicked;
    
        QtyLbl = new Label { FontSize = 11, VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, WidthRequest = 20   };
        QtyLbl.SetBinding(Entry.TextProperty, new Binding(nameof(Text), BindingMode.TwoWay, source:this));
    
        Children.Add(MinusBtn);
        Children.Add(QtyLbl);            
        Children.Add(PlusBtn);
    }
    
    private void MinusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text > 0)
            Text--;
    }
    
    private void PlusBtn_Clicked(object sender, EventArgs e)
    {
        if (Text < 10)
            Text++;
    }
    

    } This is my view-model code:

    public class CustomerDetailViewModel : BaseViewModel { public int ItemQuantity { get; set; }
    } this is how i have added my custom stepper my xaml file:

    Padding="5,0" /> I have this in my button click in the corresponding cs file:

    private async void viewOrderBtn_Clicked(object sender, EventArgs e) { var item = (CustomStepper)sender; //no idea if this is correct var qty = //not able to get the custom stepper text property.

        var itemobj = item?.BindingContext as AllProductListview;
        List<OrderModel> Orderlist = new List<OrderModel>();
        int ID = Convert.ToInt32(itemobj.PK);
        int vendorfk = Convert.ToInt32(itemobj.VendorFK);
        float price = itemobj.SalesPrice;
        float total = price * quantity;
        Orderlist.Add(new OrderModel
        {
            PK = Convert.ToInt32(itemobj.PK),
            VendorFK = Convert.ToInt32(itemobj.VendorFK),
            NameE = itemobj.NameE,
            NameC = itemobj.NameC,
            SalesPrice = itemobj.SalesPrice,
            DChargeMode = Convert.ToInt32(itemobj.DChargeMode),
            VatForm = itemobj.VatForm,
            DeliveryCharge = itemobj.DeliveryCharge,
            Quantity = quantity,
            TotalAmount = total,
            Delete = "delete.png"
        });
        if (OrderData.Count == 0)
        {
            OrderData.Add(new OrderModel
            {
                PK = Orderlist[0].PK,
                VendorFK = Orderlist[0].VendorFK,
                NameE = Orderlist[0].NameE,
                NameC = Orderlist[0].NameC,
                SalesPrice = Orderlist[0].SalesPrice,
                DChargeMode = Orderlist[0].DChargeMode,
                VatForm = Orderlist[0].VatForm,
                DeliveryCharge = Orderlist[0].DeliveryCharge,
                Quantity = Orderlist[0].Quantity,
                TotalAmount = Orderlist[0].TotalAmount,
                Delete = Orderlist[0].Delete
            });
            Isexecute = true;
        }
        else
        {
            if (vendorfk == OrderData[0].VendorFK)
            {
                for (int i = 0; i < OrderData.Count; i++)
                {
                    /*@ambi : while debugging, when i change the qty of the 1st product and added the second product:
                     * [ID value is 47 and the OrderData[i].PK value is 46]*/
                    if (ID == OrderData[i].PK)
                    {
                        OrderData[i].Quantity = Orderlist[0].Quantity;
                        OrderData[i].TotalAmount = Orderlist[0].TotalAmount;
                        IsPresent = true;
                        Isexecute = true;
                    }
                }
                if (IsPresent == false)
                {
                    int count = OrderData.Count;
                    for (int j = count - 1; j < count; j++)
                    {
                        OrderData.Add(new OrderModel
                        {
                            PK = Orderlist[0].PK,
                            VendorFK = Orderlist[0].VendorFK,
                            NameE = Orderlist[0].NameE,
                            NameC = Orderlist[0].NameC,
                            SalesPrice = Orderlist[0].SalesPrice,
                            DChargeMode = Orderlist[0].DChargeMode,
                            VatForm = Orderlist[0].VatForm,
                            DeliveryCharge = Orderlist[0].DeliveryCharge,
                            Quantity = Orderlist[0].Quantity,
                            TotalAmount = Orderlist[0].TotalAmount,
                            Delete = Orderlist[0].Delete
                        });
                    }
                    Isexecute = true;
                }
            }
            else
            {
                await DisplayAlert(LangResource.Alert, "You must order from the same dealer only.", LangResource.ok);
                Isexecute = false;
            }
        }
        // Pickerindex = -1;
        if (Isexecute)
        {
            UploadPopUpPage orderPage = new UploadPopUpPage(OrderData);
            orderPage.EventPass += OrderPage_EventPass;
            await PopupNavigation.PushAsync(orderPage);
        }
    
    }
    
    Thursday, February 13, 2020 9:05 AM

Answers

  • User392765 posted

    Hey..I got the answer.. This is how i accessed the members...

    https://stackoverflow.com/questions/60200685/not-able-to-get-the-text-property-of-custom-stepper-used-in-the-xaml-file-to-its

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Wednesday, February 19, 2020 3:49 AM

All replies

  • User382871 posted

    Change the Entry.TextProperty to Label.TextProperty because QtyLbl is the type of Label. QtyLbl = new Label { FontSize = 11, VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, WidthRequest = 20 }; QtyLbl.SetBinding(Label.TextProperty, new Binding(nameof(Text), BindingMode.TwoWay, source: this));

    when the View Order button is clicked. I am not able to access the quantity value in the custom stepper text. I create a basic demo to test the 'CustomStepper', and add a button to get the Text value. ```

    //ButtonClicked code private void ButtonClicked(object sender, EventArgs e) { Console.WriteLine("==stepper.text:" + stepper.Text.ToString()); } ```

    I tried var qty = stepper.Text. but the name stepper is not coming. How did you display the views on the page, could you post the related code of xaml? It'll help to reproduce the issue to get a solution.

    In the view order button's click event, you can get the button from sender instead of CustomStepper. private async void viewOrderBtn_Clicked(object sender, EventArgs e) { var item = (CustomStepper)sender; //no idea if this is correct var qty = //not able to get the custom stepper text property. ... } The button 's parent layout is available, to get stepper, try the following code: ``` private async void viewOrderBtn_Clicked(object sender, EventArgs e) { var button = sender as Button;

    var layout = button.Parent as StackLayout;
    foreach (var item in layout.Children)
    {
    
    }
    

    } ```

    Friday, February 14, 2020 3:05 AM
  • User392765 posted

    How did you display the views on the page, could you post the related code of xaml? It'll help to reproduce the issue to get a solution.

    Could you check if i have done the bindings correctly? I'm new to xamarin & I dont know much about about the binding scenarios..

    My xaml code : `

    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="logo" TargetType="Image">
                <Setter Property="HeightRequest" Value="80"/>
                <Setter Property="WidthRequest" Value="80"/>
                <Setter Property="Aspect" Value="AspectFit"/>
                <Setter Property="HorizontalOptions" Value="Center"/>
                <Setter Property="VerticalOptions" Value="Center"/>
            </Style>
            <Style x:Key="listlabel" TargetType="Label">
                <Setter Property="HorizontalTextAlignment" Value="Center"/>
                <Setter Property="FontSize" Value="11"/>
                <Setter Property="FontFamily" Value="Tahoma Regular font.ttf#Tahoma Regular font"/>
                <Setter Property="TextColor" Value="Black"/>
                <!--<Setter Property="FontAttributes" Value="Bold"/>   @ambi : changed this value to check-->
                <Setter Property="VerticalOptions" Value="Center"/>
            </Style>
            <Style x:Key="label" TargetType="Label">
                <Setter Property="FontSize" Value="12"/>
                <Setter Property="FontAttributes" Value="Bold"/>
                <Setter Property="TextColor" Value="Black"/>
                <Setter Property="HorizontalOptions" Value="StartAndExpand"/>
                <Setter Property="VerticalOptions" Value="Center"/>
                <Setter Property="FontFamily"  Value="Tahoma Regular font.ttf#Tahoma Regular font"/>
            </Style>
            <Style x:Key="picker" TargetType="local:XPicker">
                <Setter Property="FontSize" Value="11"/>
                <Setter Property="TextColor" Value="Black"/>
                <Setter Property="FontFamily" Value="Tahoma Regular font.ttf#Tahoma Regular font"/>
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    <NavigationPage.TitleView>
        <StackLayout Orientation="Horizontal" VerticalOptions="Center">
            <Label Text="{lang:Translate Custdashboard}" HorizontalOptions="Start" 
                   VerticalOptions="Center" FontFamily="Tahoma Regular font.ttf#Tahoma Regular font"
                   FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
            <ff:CachedImage x:Name="LangIcon"                           
                           HorizontalOptions="EndAndExpand"
                            VerticalOptions="Center"
                            CacheType="Memory"
                            HeightRequest="24"
                            WidthRequest="24"
                            Aspect="AspectFit"
                            DownsampleWidth="300"
                            Margin="10,0,10,0"><!--@ambi: edited horizontal options from end to endandexpand-->
    
                <ff:CachedImage.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
                </ff:CachedImage.GestureRecognizers>
            </ff:CachedImage>
        </StackLayout>
    </NavigationPage.TitleView>
    <ContentPage.Content>
        <Grid RowSpacing="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="40"/>
                <RowDefinition Height="*"/><!--@ambi : 2*-->
                <RowDefinition Height="40"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height=".15*"/> <!--@ambi : 2*-->
            </Grid.RowDefinitions>
            <Grid Grid.Row="0" Margin="0,-5,0,0">
                <Frame HasShadow="True" CornerRadius="10" 
                       HeightRequest="47" 
                       BackgroundColor="White"
                       HorizontalOptions="CenterAndExpand"
                       VerticalOptions="Center"
                       Padding="0"
                       Margin="7,5">
                    <StackLayout VerticalOptions="Center">
                        <SearchBar Text="{Binding SearchText}" 
                                   Placeholder="{lang:Translate SearchHere}"  
                                   FontFamily="Tahoma Regular font.ttf#Tahoma Regular font" 
                                   TextColor="#3F414D"
                                   HorizontalOptions="FillAndExpand"  
                                   FontSize="14"/>
                    </StackLayout>
                </Frame>
            </Grid>
            <Grid Grid.Row="1">
                <StackLayout VerticalOptions="FillAndExpand"  
                             HorizontalOptions="FillAndExpand">
                    <local:CustmerMap x:Name="MyMap"                  
                                      MapPosition="{Binding MyPosition}"
                                      MapPins="{Binding Pin}"
                                      IsShowingUser="true"
                                      MapType="Street" />   
                </StackLayout>
            </Grid>
            <Grid Grid.Row="2">
                <Frame HasShadow="True"
                       Margin="2" Padding="10"
                       BackgroundColor="White">
                    <Grid >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>                            
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>   <!--for qty width 0.55-->                            
                        </Grid.ColumnDefinitions>
                        <!--@ambi : Edited to translate the description, distance, quantity and price-->
                        <Label Text="{lang:Translate Description}" Style="{StaticResource label}"                                
                               Grid.Column="0" HorizontalOptions="Start"/> 
    
                        <Label Text="{lang:Translate Distance}" Style="{StaticResource label}" Grid.Column="1" HorizontalOptions="Center"/>
    
                        <Label Text="{lang:Translate Price}" Style="{StaticResource label}"  Padding="0,0,10,0"                              
                               Grid.Column="2" HorizontalOptions="End"/>
    
                        <Label Text="{lang:Translate Quantity}" Style="{StaticResource label}" Grid.Column="3" HorizontalOptions="Center"/>                        
                    </Grid>
                </Frame>
            </Grid>
            <Grid Grid.Row="3">
                <Frame HasShadow="True"
                       BackgroundColor="White"
                       Margin="1" 
                       Padding="5"> <!--@ambi : changed margin from 2 to 1 padding-10-->
                    <ListView 
                            x:Name="Prodlistview"       
                            IsGroupingEnabled="True"
                            ItemsSource="{Binding GroupedData}"  
                            GroupDisplayBinding="{Binding Key}"
                            ItemSelected="Prodlistview_ItemSelected"
                            SeparatorVisibility="Default">
    
                        <ListView.GroupHeaderTemplate>
                            <DataTemplate>
                                <ViewCell Height="5"><!--@ambi : height-15-->
                                    <StackLayout VerticalOptions="CenterAndExpand"  
                                                 Padding="0,0"    
                                                 Orientation="Horizontal"                                                 
                                                BackgroundColor="#e3e2de">
                                        <!--padding - 10  FontAttributes="Bold"-->
                                        <Label Text="{Binding Key}"                                                
                                               TextColor="Black" 
                                               VerticalOptions="CenterAndExpand" 
                                               HorizontalOptions="CenterAndExpand"
                                               FontSize="12" 
                                               Style="{StaticResource listlabel}"/>
    
                                        <Button x:Name="viewOrderBtn"
                                                Text= "{lang:Translate DriverViewOrder}"
                                                HorizontalOptions="EndAndExpand"
                                                FontAttributes="None"
                                                CommandParameter="{Binding Key}"
                                                Clicked="viewOrderBtn_Clicked"  
                                                Margin="2,5"
                                                Padding="1"
                                                FontSize="12"/> <!--@ambi : added button in the group view-->
                                        <!---->
                                    </StackLayout>
                                </ViewCell>                                
                            </DataTemplate>
    
                        </ListView.GroupHeaderTemplate>
    
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <local:ListViewSelectionColorRender SelectedBackgroundColor="Transparent">
                                    <ViewCell.View>
                                        <Grid>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="*"/>                                                
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="*"/>    <!--qty..width 0.55-->
                                            </Grid.ColumnDefinitions>
                                            <Label Grid.Column="0" Text="{Binding NameE}" 
                                                   Style="{StaticResource listlabel}" MaxLines="1" 
                                                   HorizontalTextAlignment="Start"
                                                   LineBreakMode="TailTruncation"/>
                                            <!--@ambi : HorizontalTextAlignment="Start"-->
                                            <Label Grid.Column="1" Text="{Binding distance}" Style="{StaticResource listlabel}" 
                                                   TextColor="DarkGoldenrod"/>
    
                                            <Label Grid.Column="2" Text="{Binding SalesPrice}" 
                                                   Padding="0,0,15,0"
                                                   HorizontalTextAlignment="End"
                                                   Style="{StaticResource listlabel}"/>
    
                                            <StackLayout Grid.Column="3" VerticalOptions="Center" x:Name="Container">
                                                <!--<Frame BorderColor="Gray" HeightRequest="30" WidthRequest="40" 
                                                       CornerRadius="7" Padding="5,0" Margin="0,0" HasShadow="False">
                                                    <local:BorderlessPicker x:Name="picker"
                                                                            Title="{lang:Translate Select}" 
                                                                            Style="{StaticResource picker}" 
                                                                            SelectedIndex="{Binding Pickerindex}"
                                                                            ItemsSource="{Binding QtyListModel}" 
                                                                            SelectedIndexChanged="QtyPicker_SelectedIndexChanged"                                                                                                                                              
                                                                            ItemDisplayBinding="{Binding Quantity}" 
                                                                            TextColor="Black"/>                                                    
                                                </Frame>-->                                                
                                                <!--@ambi : Custom stepper added to check a different method-->
                                                    <local:CustomStepper x:Name="stepper"                                                                           
                                                                         Text="{Binding Quantity, Source Text, Mode=TwoWay}"                                                                          
                                                                         Padding="3,0" />                                                
                                            </StackLayout>  
                                        </Grid>
                                    </ViewCell.View>
                                </local:ListViewSelectionColorRender>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Frame>
            </Grid>
            <!--@ambi: added this grid for the sisscol Footer image -->
            <Grid Grid.Row="4" >
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                </Grid.RowDefinitions>
                <Image Source="sisscol.png"  
                        HorizontalOptions="CenterAndExpand" 
                        VerticalOptions="EndAndExpand" 
                       Aspect="Fill"
                       Margin="2"/>
            </Grid>
        </Grid>        
    </ContentPage.Content>
    

    `

    Friday, February 14, 2020 3:59 AM
  • User382871 posted

    I want to multiply the price and quantity of each products under one dealer and store it in a List_model-OrderModel when the View Order button is clicked.

    You can add an Id property in viewModel class to distinguish the group item. Then get the group list by the Id in button click event to retrieve the data. Model class public class PersonList : List<Person> { public string Heading { get; set; } public string Id { get; set; } public List<Person> Persons => this; } page.xaml <ListView ItemsSource="{Binding ListOfPeople}" HasUnevenRows="True" IsGroupingEnabled="true"> <ListView.GroupHeaderTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal"> <Label Text="{Binding Id}" IsVisible="False"/> <Label Text="{Binding Heading}" /> <Button Clicked="Button_Clicked" WidthRequest="50" HeightRequest="30" HorizontalOptions="EndAndExpand"/> </StackLayout> </ViewCell> </DataTemplate> </ListView.GroupHeaderTemplate> ... </ListView>

    ButtonClicked event: ``` private void ButtonClicked(object sender, EventArgs e) { var button = sender as Button; var layout = button.Parent as StackLayout;

    Label label = layout.Children[0] as Label;
    
    foreach (var item in ListOfPeople)
    {
        var personList = item as PersonList;
    
        if (personList.Id == label.Text)
        {
            var list = personList.Persons as List<Person>;
            foreach (var _item in list)
            {
                //opearte the data
                var person = _item as Person;
    
                Console.WriteLine("==Person.FirstName:" + person.FirstName);
            }
        }
    }
    

    } ```

    Friday, February 14, 2020 7:54 AM
  • User392765 posted

    Thanks for the effort. but what i want is to get the text value of the custom stepper in the listview in my cs file. Its difficult to get the custom controls property that is placed inside the list view.

    Friday, February 14, 2020 9:08 AM
  • User382871 posted

    but what i want is to get the text value of the custom stepper in the listview in my cs file. Please check the sample code, it could achieve the function you descriped. When clicking the button in the header template, the data of the project will be retrieved in a cs file.

    Monday, February 17, 2020 2:07 AM
  • User392765 posted

    @Jarvan I tried the below code and while debugging, item.BindingContext has the details under the heading. How do i multiply the price and quantity and add it to the OrderModel ? Tried var total = productList.SalesPrice * productList.Quantity; it doesnt work. shows an exception `System.NullReferenceException: 'Object reference not set to an instance of an object.'

         private async void viewOrderBtn_Clicked(object sender, EventArgs e)
                    {
                       /* item.BindingContext contains all the values [whn i did step by step *debugging] as in AllProductListview..now I have to put it in a loop and *calculate the total by multiplying the price and quantity and store it in *OrderModel by adding the record into the Orderlist */
            var item = (Button)sender;
            var itemobj = item?.BindingContext as AllProductListview;
            List<OrderModel> Orderlist = new List<OrderModel>();
            int ID = Convert.ToInt32(itemobj.PK); //showing no value assigned
            int vendorfk = Convert.ToInt32(itemobj.VendorFK); //showing no value assigned
            float price = itemobj.SalesPrice; //showing no value assigned
            int quantity = itemobj.Quantity; //showing no value assigned
            float total = price * quantity;
                }
    
    Monday, February 17, 2020 5:48 AM
  • User382871 posted

    shows an exception `System.NullReferenceException: 'Object reference not set to an instance of an object.'

    The BindingContext is set for the page, it cannot be get from button. You can add a breakpoint to vertify that.

    Tuesday, February 18, 2020 2:35 AM
  • User392765 posted

    Hey..I got the answer.. This is how i accessed the members...

    https://stackoverflow.com/questions/60200685/not-able-to-get-the-text-property-of-custom-stepper-used-in-the-xaml-file-to-its

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Wednesday, February 19, 2020 3:49 AM