简体   繁体   中英

Xamarin Forms Event

I am new to Xamarin and C#.

Firstly I am Showing my view customer.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:gridlook="clr-namespace:BlankApp5.Helpers"
             xmlns:syncfusion="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms" 
             x:Class="BlankApp5.Views.Customer">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="SAVE AS PDF" Order="Secondary" Clicked="SaveAsPdf"  />
    </ContentPage.ToolbarItems>

    <ContentPage.Resources>
        <ResourceDictionary>
            <gridlook:Gridhelp x:Key="gridhelp" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>

                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>

            <syncfusion:SfDataGrid 
                Grid.Row="0"
                x:Name="dataGrid_cust"
            GridStyle="{StaticResource gridhelp}"  
            ItemsSource="{Binding Customer_data}"
            ColumnSizer="Star"

            AutoGenerateColumns="False"       
            AllowSorting="True"
            SelectionMode="Single"
            GridTappedCommand="{Binding Tapped}"                      
            EnableDataVirtualization="True"
            AllowResizingColumn="True">

                <syncfusion:SfDataGrid.Columns
                x:TypeArguments="syncfusion:Columns">


                    <syncfusion:GridTextColumn HeaderText="Cust ID" 
                                      HeaderFontAttribute="Bold"                                
                                   MappingName="Id" />
                    <syncfusion:GridTextColumn MappingName="Name" HeaderFontAttribute="Bold"/>

                    <syncfusion:GridTextColumn HeaderText="Balance"
                                           HeaderFontAttribute="Bold" 
                                   MappingName="CurrentBalance" />


                </syncfusion:SfDataGrid.Columns>
            </syncfusion:SfDataGrid>

            <Grid Grid.Row="1"
                  BackgroundColor="Gray">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="2*"/>
                </Grid.ColumnDefinitions>

                <Label
                    Grid.Column="0"
                    Text="TOTAL BALANCE"
                    TextColor="Black"
                    FontAttributes="Bold"
                    VerticalOptions="Center"
                />
                <Label
                    Grid.Column="1"
                    Text="{Binding Total}"
                    TextColor="Black"
                    HorizontalOptions="End"
                    FontAttributes="Bold"
                    VerticalOptions="Center"/>
            </Grid>
        </Grid>
    </ContentPage.Content>

</ContentPage>

As you can see a Clicked event in Toolbar items

Now I'll show the code behind

          public partial class Customer : ContentPage
                {
                    public Customer()
                    {
                        InitializeComponent();
                    }
                    private void SaveAsPdf(object sender, EventArgs e)
                    {
                        DataGridPdfExportingController pdfExport = new DataGridPdfExportingController();
        pdfExport.HeaderAndFooterExporting += PdfExport_HeaderAndFooterExporting;
                        MemoryStream stream = new MemoryStream();
                        var pdfDoc = new PdfDocument();
                        PdfPage page = pdfDoc.Pages.Add();
                        PdfGraphics graphics = page.Graphics;

                        var exportToPdfGrid = pdfExport.ExportToPdfGrid(this.dataGrid_cust, this.dataGrid_cust.View, new DataGridPdfExportOption()
                        {
                            FitAllColumnsInOnePage = true,



                        }, pdfDoc);

                        PdfStringFormat drawFormat = new PdfStringFormat();
                        drawFormat.WordWrap = PdfWordWrapType.Word;
                        drawFormat.Alignment = PdfTextAlignment.Center;
                        drawFormat.LineAlignment = PdfVerticalAlignment.Top;


                        PdfStringFormat drawFormatright = new PdfStringFormat();
                        drawFormatright.WordWrap = PdfWordWrapType.Word;
                        drawFormatright.Alignment = PdfTextAlignment.Right;
                        drawFormatright.LineAlignment = PdfVerticalAlignment.Top;

                        //Set the font. 
                        PdfFont fontco = new PdfStandardFont(PdfFontFamily.Helvetica,20f,PdfFontStyle.Bold);
                        PdfFont fonthe = new PdfStandardFont(PdfFontFamily.Helvetica,15f,PdfFontStyle.Bold);

                        //Create a solid brush. 
                        PdfBrush brush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.Black));
                        RectangleF bounds = new RectangleF(new PointF(10, 10), new SizeF(page.Graphics.ClientSize.Width - 30, page.Graphics.ClientSize.Height ));

                        graphics.DrawString(CheckFirst.CompData[0], fontco, brush, bounds.X+240 ,bounds.Y , drawFormat);
                        graphics.DrawString(CheckFirst.CompData[1], fonthe, brush, bounds.X+20, bounds.Y + 35, drawFormat);
                        graphics.DrawString(CheckFirst.CompData[1], fonthe, brush, page.Graphics.ClientSize.Width-30, bounds.Y + 35, drawFormat);
                        exportToPdfGrid.Draw(page, new PointF(10, 80));

                        pdfDoc.Save(stream);
                        pdfDoc.Close(true);
                        if (Device.RuntimePlatform == "WinPhone" || Device.RuntimePlatform == "Windows")
                        {
                            Xamarin.Forms.DependencyService.Get<ISaveWidowsPhone>().Save(CheckFirst.CompanyName+"_CUSTOMER_REPORT.pdf", "application/pdf", stream);
                        }
                        else
                            Xamarin.Forms.DependencyService.Get<ISave>().Save(CheckFirst.CompanyName + "_CUSTOMER_REPORT.pdf", "application/pdf", stream);
                    }




     private void PdfExport_HeaderAndFooterExporting(object sender, PdfHeaderFooterEventArgs e)
            {
                PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f, PdfFontStyle.Bold);
                var width = e.PdfPage.GetClientSize().Width;


 PdfPageTemplateElement header = new PdfPageTemplateElement(width, 38);
                header.Graphics.DrawString("Order Details", font, PdfPens.Black, 70, 3);
                e.PdfDocumentTemplate.Top = header;



  PdfPageTemplateElement footer = new PdfPageTemplateElement(width, 38);
                footer.Graphics.DrawString("Order Details", font, PdfPens.Black, 70, 3);
                e.PdfDocumentTemplate.Bottom = footer;
            }

                }
            }

The code executes without any error but

 pdfExport.HeaderAndFooterExporting += PdfExport_HeaderAndFooterExporting;

This line doesn't take the execution to the event I defined below. I tried with breaking points. The line is executed but it never passes the executuion to the

private void PdfExport_HeaderAndFooterExporting(object sender, PdfHeaderFooterEventArgs e)

Registering and Invoking an event are 2 different things. I would suggest you to register your event in the constructor, with: (the deregistration is just a best practice)

pdfExport.HeaderAndFooterExporting -= PdfExport_HeaderAndFooterExporting;
pdfExport.HeaderAndFooterExporting += PdfExport_HeaderAndFooterExporting;

And Invoke it where you need it (in the Event SaveAsPdf, instead of your current registration) with:

HeaderAndFooterExporting?.Invoke (this, null);

Actually you are registering an event here not invoking it. Check this

Subscribe and unsubscribe events in C#

Registering event is not like invoking a function or method. In order to invoke a event you've to do

HeaderAndFooterExporting?.Invoke (this, null);

Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM