Search This Blog

Tuesday, October 29, 2013

Display SplashScreen From Resource File WPF


WPF > Windows > SplashScreen 

SplashScreen shows an image when a WPF application starts or in a startup window.
Call the Show method to display the splash screen.
Supported image format: BMP, GIF, JPEG, PNG, TIFF.

Example:

var splashScreen = new SplashScreen( resourceName : "Resources/loading1.gif");
splashScreen.Show(false);

Monday, October 28, 2013

Set StartUp Window or Page WPF

WPF  > Windows > Application > StartupUri

StartupUri gets or sets a UI that is automatically shown when an application starts.

Example

StartUp Window or Page WPF

Open App.xaml file and change StartupUri.

<Application x:Class="DataGrid.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="winMain.xaml">
    <Application.Resources>
     </Application.Resources>
</Application>

Data Binding in WPF

WPF  Data Binding

With Data binding in WPF you can take data from any property of an object and bind it to other dependency property of another object.
Data binding copies a value from a source object to a property on a destination object.
WPF object has change notification.
When the source change, the destination property will automatically be updated.

Simple example:

<Grid>
        <Grid.RowDefinitions >
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox Name="Source" Grid.Row="0" >Source</TextBox>
        <TextBlock Grid.Row="1">
            <TextBlock.Text>
                <Binding ElementName="Source" Path="Text"  />
            </TextBlock.Text>
        </TextBlock>
</Grid>

Binding modes

OneWay
  • source -> destination
OneWayToSource
  • destination - > source
OneWayToSource
  • destination - > source
OneTime

  • source - > destination (the property is initially set, but updates to the source are not copied to the destination)
TwoWay

  • source -> destination
  • destination - > source
Other examples:

SQL Server datagrid view,update, delete data


 

Printing in WPF

WPF > Printing

Windows Presentation Foundation (WPF) have a rich set of printing and print system management APIs. 
The core of this new functionality is the new XML Paper Specification (XPS) file format and the XPS print path.

Example: Printing a Visual
XAML:
<Window x:Class="Printing.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="Grid">
        <Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="91,63,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="75,197,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
     </Grid>
</Window>
Code:
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)

{
    printDialog.PrintVisual(Grid, "My First Print Example");
}

PrintVisual Method WPF

WPF > Printing > PrintVisual

PrintVisual method prints a visual  object to the PrintQueue.

Parameters
  • visual: object to be print
  • description: description of the job that is to be printed

Examples:

Print DataGrid WPF

WPF > Printing > DataGrid

Print DataGrid WPF Example

PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(dgProducts, "Grid Printing.");


SQL Example WPF Datagrid to View, Update, Insert and Delete data

WPF > ControlsItemsControl > DataGrid > SQL Server example

Using WPF Datagrid to View, Update, Insert and Delete data
In the following example I will show you how to use DataGrid to display, edit, add and delete data from SQL Server Database and ADO.NET Entity Data Model Designer.


Step 1: Create a new project in Visual Studio: and select WPF Application







Step 2:  Create SQL Server database and Product sample table

Go to left Pane in SQL Server Object Explorer and create a new database named Invoices


 Create new table name Product using the following script

CREATE TABLE [dbo].[Products] (
    [Id]                    INT            IDENTITY (1, 1) NOT NULL,
    [ProductCode]           NVARCHAR (MAX) NOT NULL,
    [ProductDescription]    NVARCHAR (MAX) NOT NULL,
    [ProductPrice]          FLOAT (53)     NOT NULL,
    [ProductExpirationDate] SMALLDATETIME  NULL,
    [ProductStockQuantity]  INT            NULL,
    [ProducVatRate]         FLOAT (53)     DEFAULT ((0)) NOT NULL,
    [IsBio]                 BIT            DEFAULT ((0)) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
  

Step 3: Create ADO.Net Entity Data Model

Go to solution explorer and create a new folder named DAL (Data Access Layer) and then Right click and add new ADO.Net Entity Data Model.



 Connect to your database and add Products table to your model
Step 4: XAML File

<Window x:Name="Main" x:Class="DataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="623" Loaded="Main_Loaded">
    <Grid>
        <DataGrid x:Name="dgProducts" HorizontalAlignment="Left" Margin="10,31,0,0" VerticalAlignment="Top"
                   ItemsSource="{Binding}"   AutoGenerateColumns="False" RowEditEnding="dgProducts_RowEditEnding" AddingNewItem="dgProducts_AddingNewItem" BeginningEdit="dgProducts_BeginningEdit" PreviewKeyDown="dgProducts_PreviewKeyDown" Width="595" AlternatingRowBackground="{DynamicResource {x:Static SystemColors.ActiveCaptionBrushKey}}" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                    Width="75" Header="Product ID" IsReadOnly="True" />
                <DataGridTextColumn Binding="{Binding ProductCode, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                    Width="100" Header="Code"/>
                <DataGridTextColumn Binding="{Binding ProductDescription, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                    Width="100" Header="Description"/>
                <DataGridTextColumn  Binding="{Binding ProductPrice, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                    Width="100" Header="Price"/>
                <DataGridTemplateColumn Header="Expiration date">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding ProductExpirationDate, StringFormat=\{0:d\}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <DatePicker SelectedDate ="{Binding ProductExpirationDate, NotifyOnSourceUpdated=True,Mode=TwoWay,
                                UpdateSourceTrigger=PropertyChanged}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
                <DataGridCheckBoxColumn Binding="{Binding IsBio, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                    Width="100" Header="Bio"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Step 5: Code file:

using DataGrid.DAL;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DataGrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        InvoicesEntities context = new InvoicesEntities();
        bool isInsertMode = false;
        bool isBeingEdited = false;

        public MainWindow()
        {
            InitializeComponent();
        }
        private void Main_Loaded(object sender, RoutedEventArgs e)
        {
            dgProducts.ItemsSource = GetProductList();
        }
        private ObservableCollection<Products> GetProductList()
        {
            var list = from e in context.Products select e;
            return new ObservableCollection<Products>(list);
        }
        private void dgProducts_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            Products product = new Products();
            Products curProd = e.Row.DataContext as Products;
            if (isInsertMode)
            {
                var InsertRecord = MessageBox.Show("Do you want to add " + curProd.ProductCode  + " as a new product?", "Confirm", MessageBoxButton.YesNo,

                    MessageBoxImage.Question);
                if (InsertRecord == MessageBoxResult.Yes)
                {
                    product.ProductCode = curProd.ProductCode;
                    product.ProductDescription = curProd.ProductDescription;
                    product.ProductPrice = curProd.ProductPrice;
                    product.ProductExpirationDate = curProd.ProductExpirationDate;
                    context.Products.Add(product);
                    context.SaveChanges();
                    dgProducts.ItemsSource = GetProductList();
                    MessageBox.Show(product.ProductCode + " " + product.ProductDescription + " has being added!", "Add product", MessageBoxButton.OK, MessageBoxImage.Information);
                    isInsertMode = false;

                }
                else
                    dgProducts.ItemsSource = GetProductList();
            }
            context.SaveChanges();
        }
        private void dgProducts_AddingNewItem(object sender, AddingNewItemEventArgs e)
         {
            isInsertMode = true;
        }
        private void dgProducts_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            isBeingEdited = true;
        }
        private void dgProducts_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete && !isBeingEdited)
            {
                if (dgProducts.SelectedItems.Count > 0)
                {
                    var Res = MessageBox.Show("Are you sure you want to delete " + dgProducts.SelectedItems.Count + " products?", "Deleting products",
                        MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                    if (Res == MessageBoxResult.Yes)
                    {
                        foreach (var row in dgProducts.SelectedItems)
                        {
                            Products product = row as Products;
                            context.Products.Remove(product);
                        }
                         context.SaveChanges();
                        MessageBox.Show(dgProducts.SelectedItems.Count + " Products have being deleted!");
                    }
                    else
                        dgProducts.ItemsSource = GetProductList();
                }
            }
        }
    }
}