Search This Blog

Showing posts with label Binding. Show all posts
Showing posts with label Binding. Show all posts

Thursday, May 4, 2017

Bind Width to another Width control WPF

WPF > Binding > Width

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition 
Width="{Binding ElementName=controlName, Path=ActualWidth}"/>
  </Grid.ColumnDefinitions>

Monday, May 19, 2014

WPF Converter Example

WPF > Data > Converters

Converters changes data from one type to another and apply custom logic to binding.
Implementation : create a class that implements the IvalueConverter.

Example:


XAML:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:YesNoConverter x:Key="YesNoConverter" />
    </Window.Resources>
    <StackPanel Margin="5">
        <CheckBox x:Name="chk" IsChecked="{Binding ElementName=txtYesNo, Path=Text, Converter={StaticResource YesNoConverter}}" Content="Yes/No" />
        <TextBox Name="txtYesNo" />
    </StackPanel>
</Window>

C# Code:

using System;
using System.Collections.Generic;
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 WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///
    public class YesNoConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch (value.ToString())
            {
                case "Yes":
                    return true;
                case "No":
                    return false;
            }
            return false;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                if ((bool)value == true)
                    return "Yes";
                else
                    return "No";
            }
            return "No";
        }
    }
    public partial class MainWindow : Window
    {
     
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}



Binding path to current source WPF

WPF > Binding > Path

What is Binding Path=. ?

Answer:

A period (.) path can be used to bind to the current source.

Tuesday, November 19, 2013

WPF Binding to Web Service Example

WPF > Binding > Web Service

Add reference to your Web service. We will use com.microsoft.msdn.services as example:

 


XAML:


<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300"
       xmlns:src="clr-namespace:WpfApplication2"
        >
    <Grid>
        <ListView  ItemsSource="{Binding Path=availableVersionsAndLocales}" HorizontalAlignment="Left" Height="240" VerticalAlignment="Top" Width="266">
            <ListView.View>
                <GridView>
                    <GridViewColumn  DisplayMemberBinding="{Binding Path=locale}" Header="Locale" />
                    <GridViewColumn  DisplayMemberBinding="{Binding Path=version}" Header="Version" />
                </GridView>
            </ListView.View>
        </ListView>
   </Grid>
</Window>

C# Code:

using WpfApplication2.com.microsoft.msdn.services;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            getContentRequest request = new getContentRequest();
            request.contentIdentifier = "abhtw0f1";
            ContentService proxy = new ContentService();
            this.DataContext = proxy.GetContent(request);
        }
    }
}

Result:


Monday, October 28, 2013

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


 

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