b

Sunday, 30 December 2012

How to perform WPF Data Binding using LINQ to XML vb.net

How to perform WPF Data Binding using LINQ to XMLvb.net


Step 1) Create WPF project using vb.net 4.0/4.5
Step 2) Add  Xml file to Project . name it as salesorder.xml
<?xml version="1.0" encoding="utf-8" ?>

<HeaderLines>
  <SalesOrder>
    <Header Date="17-02-04" Type="Quote">
      <SellTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </SellTo>
     <BillTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </BillTo>
     <Lines>
       <Item PartNum="LS-150">
         <ProductName>Loudspeaker, Cherry, 150W</ProductName>
         <Quantity>8</Quantity>
         <UnitPrice>12900</UnitPrice>
         <ShipmentDate />
         <Comment>Confirm the voltage is 75W</Comment>
       </Item>
          <Item PartNum="LS-MAN-10">
          <ProductName>Manual for Loudspeakers</ProductName>
          <Quantity>20</Quantity>
            <UnitPrice>100</UnitPrice>
          <ShipmentDate />
          <Comment />
       </Item>
          <Item PartNum="LS-2">
            <ProductName>Cables for Loudspeakers</ProductName>
            <Quantity>10</Quantity>
            <UnitPrice>2100</UnitPrice>
            <ShipmentDate />
            <Comment />
            </Item>
     </Lines>
     <Contact>Mr. Andy Toal</Contact>
     <Terms>14 days</Terms>
    </Header>
  </SalesOrder>
</HeaderLines>
Step 3)  Add datagrid to XAML

        <DataGrid x:Name="datagrid4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="218" Width="275" Margin="10,53,0,0"/>
        <Label Content=" Datagrid Binding in WPF using LINQ to XML" HorizontalAlignment="Left" VerticalAlignment="Top" Height="48" Width="290" Foreground="Aquamarine" FontSize="20"/>
 

Step 4)   LINQ TO XML in WPF

       
Private Function XMLDemo() As Public
            InitializeComponent()
            LoadXml()
End Function


        Private  Sub LoadXml()
            Try
                Dim doc As XDocument =  XDocument.Load("SalesOrder.xml")
                If doc Is Nothing Then
                     MessageBox.Show("doc is null")
                End If
                var query = from ele Function doc.Descendants(ByVal"Item") As in
                                ProductName = ele.Element("ProductName").Value,
                                Quanity = ele.Element("Quantity").Value,
                                UnitPrice = ele.Element("UnitPrice").Value,
                                Total = Convert.ToInt32(ele.Element("Quantity").Value) *
                                        Convert.ToDouble(ele.Element("UnitPrice").Value)
                End Function

                datagrid4.ItemsSource = query.ToList()'Binding linq to xml list to datagrid
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                MessageBox.Show(ex.InnerException.Message)
            End Try

        End Sub



Step 5) Run the Applictaion

How to perform WPF Data Binding using LINQ to XML

How to perform WPF Data Binding using LINQ to XML C#


Step 1) Create WPF project using C# 4.0/4.5
Step 2) Add  Xml file to Project . name it as salesorder.xml
<?xml version="1.0" encoding="utf-8" ?>

<HeaderLines>
  <SalesOrder>
    <Header Date="17-02-04" Type="Quote">
      <SellTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </SellTo>
     <BillTo CountryRegion="GB">
       <Name>The Cannon Group PLC</Name>
       <Address>192 Market Square</Address>
       <City>Birmingham</City>
       <Zip>B27 4KT</Zip>
     </BillTo>
     <Lines>
       <Item PartNum="LS-150">
         <ProductName>Loudspeaker, Cherry, 150W</ProductName>
         <Quantity>8</Quantity>
         <UnitPrice>12900</UnitPrice>
         <ShipmentDate />
         <Comment>Confirm the voltage is 75W</Comment>
       </Item>
          <Item PartNum="LS-MAN-10">
          <ProductName>Manual for Loudspeakers</ProductName>
          <Quantity>20</Quantity>
            <UnitPrice>100</UnitPrice>
          <ShipmentDate />
          <Comment />
       </Item>
          <Item PartNum="LS-2">
            <ProductName>Cables for Loudspeakers</ProductName>
            <Quantity>10</Quantity>
            <UnitPrice>2100</UnitPrice>
            <ShipmentDate />
            <Comment />
            </Item>
     </Lines>
     <Contact>Mr. Andy Toal</Contact>
     <Terms>14 days</Terms>
    </Header>
  </SalesOrder>
</HeaderLines>
Step 3)  Add datagrid to XAML

        <DataGrid x:Name="datagrid4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="218" Width="275" Margin="10,53,0,0"/>
        <Label Content=" Datagrid Binding in WPF using LINQ to XML" HorizontalAlignment="Left" VerticalAlignment="Top" Height="48" Width="290" Foreground="Aquamarine" FontSize="20"/>
 

Step 4)   LINQ TO XML in WPF

        public XMLDemo()
        {
            InitializeComponent();
            LoadXml();
        }


        void LoadXml()
        {
            try
            {
                XDocument doc = XDocument.Load("SalesOrder.xml");
                if (doc == null) MessageBox.Show("doc is null");
                var query = from ele in doc.Descendants("Item")
                            select new
                            {
                                ProductName = ele.Element("ProductName").Value,
                                Quanity = ele.Element("Quantity").Value,
                                UnitPrice = ele.Element("UnitPrice").Value,
                                Total = Convert.ToInt32(ele.Element("Quantity").Value) *
                                        Convert.ToDouble(ele.Element("UnitPrice").Value)
                            };
                datagrid4.ItemsSource = query.ToList();//Binding linq to xml list to datagrid
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.InnerException.Message);
            }

        }
Step 5) Run the Applictaion

Friday, 28 December 2012

WPF Button with Image and text and ToolTip

WPF Button with Image and  text and ToolTip


<Button Content="Load" HorizontalAlignment="Left" Margin="114,212,0,0" VerticalAlignment="Top" Width="213" Height="36" x:Name="Load" Click="Load_Click">
           
            <Button.ContentTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                    <Image Source="Mitsubishi Galant.jpg" Width="50"></Image>
                        <TextBlock Width="121" VerticalAlignment="Center"> Mitsubishi...</TextBlock>
                    </StackPanel>
                </DataTemplate>
            </Button.ContentTemplate>
            <Button.ToolTip>
                <StackPanel>
               
                <TextBlock>
                        <TextBlock.Text>Tooltip for Button</TextBlock.Text>
                        <TextBlock.Effect>
                            <BlurEffect>
                            </BlurEffect>
                        </TextBlock.Effect>
                        <TextBlock.FontSize>20</TextBlock.FontSize>
                 </TextBlock>
                       
                </StackPanel>
            </Button.ToolTip>
        </Button>

WPF button demo

how to bind json data to datagrid in wpf VB.NET

how to bind json data to datagrid in wpf VB.NET


  • Create a WPF Project using VB.NET 4.0/4.5
  • Add datagrid to XAML
  • Add a class equivalent to  JSON object
  • Deserialize JSON object to class in WPFVB.NET
  • Bind list to datagrid.
  • run the application.

Step 3) Adding class Equivalent to JSON object returning from WCF See this article

  
 Public Class wrapper
       Public Property salesperson() As List<SalesPerson>
       End Property
 End Class


    Public Class SalesPerson
        Public Property id() As String
        End Property
        Public Property rowOrder() As Integer
        End Property
        Public Property BusinessEntityID() As int?
        End Property
        Public Property Bonus() As decimal?
        End Property
        Public Property CommissionPct() As decimal?
        End Property
        Public Property SalesLastYear() As decimal?
        End Property
        Public Property SalesYTD() As decimal?
        End Property
        Public Property TerritoryID() As int?
        End Property
        Public Property ModifiedDate() As DateTime?
        End Property
    End Class



Step 4)  Deserialize JSON data to VB.NET class

                 Dim req As WebRequest =  WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableJson")
                req.ContentType = "application/json"
                Dim resp As WebResponse =  req.GetResponse()
                Dim stream As Stream =  resp.GetResponseStream()
                Dim re As StreamReader =  New StreamReader(stream)
                Dim json As String =  re.ReadToEnd() 
'Note: WCF returns anonymous array list , so we need to append class name manually. In this case SalesPerson is the class name.

                json = "{\"SalesPerson\":" + json + "}"
                Dim w As wrapper = CType(New JavaScriptSerializer().Deserialize(json,Type.GetType(wrapper)), wrapper)


Step 5) Bind it to DataGrid

           datagrid1.ItemsSource = w.salesperson;

Step 6) Add namespaces
Imports System.IO;
Imports System.Net;
Imports System.Web.Script.Serialization;

Step 7) Run the Application

how to bind json data to datagrid in wpf C#

how to bind json data to datagrid in wpf C#


  • Create a WPF Project using C# 4.0/4.5
  • Add datagrid to XAML
  • Add a class equivalent to  JSON object
  • Deserialize JSON object to class in WPF C#
  • Bind list to datagrid.
  • run the application.

Step 3) Adding class Equivalent to JSON object returning from WCF See this article

    public class wrapper
    {
       public List<SalesPerson> salesperson { get; set; }
    }


    public class SalesPerson
    {
        public String id { get; set; }
        public int rowOrder { get; set; }
        public int? BusinessEntityID { get; set; }
        public decimal? Bonus { get; set; }
        public decimal? CommissionPct { get; set; }
        public decimal? SalesLastYear { get; set; }
        public decimal? SalesYTD { get; set; }
        public int? TerritoryID { get; set; }
        public DateTime? ModifiedDate { get; set; }
    }
Step 4)  Deserialize JSON data to C# class

                WebRequest req = WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableJson");
                req.ContentType = "application/json";
                WebResponse resp = req.GetResponse();
                Stream stream = resp.GetResponseStream();
                StreamReader re = new StreamReader(stream);
                String json = re.ReadToEnd();
                json = "{\"SalesPerson\":" + json + "}";
                wrapper w = (wrapper)new JavaScriptSerializer().Deserialize(json, typeof(wrapper));

Step 5) Bind it to DataGrid

           datagrid1.ItemsSource = w.salesperson;

Step 6) Add namespaces
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

Step 7) Run the Application

Thursday, 27 December 2012

How to return a datatable from a wcf service rest C#

How to return a datatable from a wcf service rest C#

This example returns datatable from WCF rest service,and consumes in 
WPF client using xml deserialization


  • Create a WCF Service Application
  • Add WCF Service name it as IRESTWCF
    • Add a method called DataTable GetDataTableXml() 
    • [ServiceContract]
          public interface IRestWCF
          {

              [OperationContract]
              [WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
              DataTable GetDataTableXml();

          }
    • Service Implementation class
    public class RestWCF : IRestWCF                       {
                              public DataTable GetDataTableXml()      {

DataTable salesdata = new DataTable("SalesPerson");
    •           try
                {
                    using (SqlConnection conn = new SqlConnection(@"server=(local)\sqlexpress2012;database=AdventureWorks2012;uid=sa;pwd=password&"))
                    {
                        using (SqlDataAdapter adapter = new SqlDataAdapter("select * from [AdventureWorks2012].[Sales].[SalesPerson]", conn))
                        {
                            adapter.Fill(salesdata);

                            salesdata.AcceptChanges();
                            conn.Close();
                        }
                    }
                }
                catch (SqlException ex)
                {
                    throw ex;
                }
                salesdata.RemotingFormat = SerializationFormat.Xml;
                return salesdata;

            }
                  }

  • Web.config
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="restbeh">
          <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="true" />
          <serviceMetadata  httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restendbeh">
          <!--<soapProcessing processMessages="True"/>-->
          <webHttp helpEnabled="True" faultExceptionEnabled="True" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Xml"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="myrestbinding">
          <security mode="None"></security>
          <readerQuotas maxArrayLength="65536"/>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="WCFServicesREST.RestWCF" behaviorConfiguration="restbeh">
        <endpoint  contract="WCFServicesREST.IRestWCF" binding="webHttpBinding"  bindingConfiguration="myrestbinding"
                   behaviorConfiguration="restendbeh"></endpoint>
       
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="True"/>
  </system.serviceModel>
  <system.webServer>
 </configuration>





Consuming  in WPF Application

  • Create a WPF Application using .NET 4.0/4.5 using C#
  • Add a DataGrid to XAML name it as datagrid1
  • Add namespaces in .cs file
    • using System.Xml;
    • using System.Xml.Serialization;
    • using System.Net;
    Declare a class called SalesPerson class for XML Serialization/DeSerialization.
[XmlRoot(ElementName = "SalesPerson", Namespace = "")]
    public class SalesPerson
    {
        [XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")]
        public String id { get; set; }
        [XmlAttribute(Namespace = "urn:schemas-microsoft-com:xml-msdata")]
        public int rowOrder { get; set; }

        [XmlElement]
        public int? BusinessEntityID { get; set; }
        [XmlElement]
        public decimal? Bonus { get; set; }
        [XmlElement]
        public decimal? CommissionPct { get; set; }
        [XmlElement]
        public decimal? SalesLastYear { get; set; }
        [XmlElement]
        public decimal? SalesYTD { get; set; }
        [XmlElement]
        public int? TerritoryID { get; set; }
        [XmlElement]
        public DateTime? ModifiedDate { get; set; }
    }
Note: Each element in this class should match columns returned from wcf  Datatable, column names are case sensitive. null columns should use ?. Namespaces also must match, otherwise "serialization error saying <SalesPerson xmlns=''> not expected here" will appear.

Because WCF Rest doesn't serve proxy class. So You need ti call WebRequest/HttpWebRequest in System.Net.

as shown below

WebRequest req = WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableXml");
                  req.ContentType = "text/xml";
                    WebResponse resp = req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    XmlSerializerFactory fact = new XmlSerializerFactory();

                    XmlReader re = XmlReader.Create(stream);
                    while (re.Read())
                    {
                        if (re.NodeType == XmlNodeType.Element &&   re.LocalName.Equals("SalesPerson"))
                        {
                            XmlSerializer ser = fact.CreateSerializer(typeof(SalesPerson));

                            SalesPerson p = (SalesPerson)ser.Deserialize(re);
                           //add to list.
                            salesPersonXML.Add(p);
                        }
                    }
//Bind to datagrid in WPF
                    datagrid1.ItemsSource = salesPersonXML;

OUTPUT

How to Consume WCF REST Datatable XML in WPF

How to Consume WCF REST Datatable XML in WPF

Step 1)

Wednesday, 26 December 2012

Ivalueconverter color converter in wpf Vb.net

Ivalueconverter color converter in wpf

Step1) Create a WPF Project
Step 2) Add a datagrid to XAML

Step 3) Add a class
  
 Public Class ColorDemo
        Public Property ID() As Integer
        End Property
        Public Property color() As String
        End Property
      End Class


Step 4) Build data

  Private  Sub BuildData()
            listColor.Add(New ColorDemo
            {
                 ID=1, color="red"
            }
)
            listColor.Add(New ColorDemo
            {
                 ID = 2, color = "green"
            }
)
            listColor.Add(New ColorDemo
            {
                 ID = 3, color = "blue"
            }
)

End Sub

Step 5) Add a class for Color Conversion

Namespace SilverlightApplication1
    Public Class colorconv
     Implements IValueConverter

        Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object
            Dim cc As String =  value as String
            String xamlString = "<Canvas xmlns=\"http:'schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+cc+"\"/>";
            Dim c As Canvas = CType(System.Windows.Markup.XamlReader.Load(xamlString), Canvas)
            Dim mistyRoseBrush As SolidColorBrush = CType(c.Background, SolidColorBrush)
            Dim mistyRose As Color =  mistyRoseBrush.Color
            Dim b As SolidColorBrush =  New SolidColorBrush(mistyRose)
            Return b

        End Function

        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object
            Throw New NotImplementedException()
        End Function
    End Class
End Namespace

Step 6)  Bind List data to dataGrid

Private  Sub Bind()
            dataGrid1.ItemsSource = listColor
End Sub

Step 7) Run the Application
               Output:



Complete Source Code

Page1.xaml.cs

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Navigation

Namespace SilverlightApplication1
    Public partial Class Page1
     Inherits Page
        Dim listColor As List<ColorDemo> =  New List<ColorDemo>()
        Public  Sub New()
            InitializeComponent()
            BuildData()
            Bind()
        End Sub

        ' Executes when the user navigates to this page.
        Protected Overrides  Sub OnNavigatedTo(ByVal e As NavigationEventArgs)
        End Sub

        Private  Sub Bind()
            dataGrid1.ItemsSource = listColor
        End Sub
        Private  Sub BuildData()
            listColor.Add(New ColorDemo
            {
                 ID=1, color="red"
            }
)
            listColor.Add(New ColorDemo
            {
                 ID = 2, color = "green"
            }
)
            listColor.Add(New ColorDemo
            {
                 ID = 3, color = "blue"
            }
)

            Dim c As Color =  Color.FromArgb(255,255,255,0)
            'rectangle1.Fill = new SolidColorBrush(c);
        End Sub
    End Class


    Public Class ColorDemo
        Public Property ID() As Integer
        End Property
        Public Property color() As String
        End Property
    End Class
End Namespace


Page.xaml
<navigation:Page x:Class="SilverlightApplication1.Page1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
               
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page1 Page" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:sp="clr-namespace:SilverlightApplication1"
                 >
    <Grid x:Name="LayoutRoot">
        <Grid.Resources>
            <sp:colorconv x:Key="colorLocal"></sp:colorconv>
        </Grid.Resources>
            <sdk:DataGrid AutoGenerateColumns="False" Height="144" HorizontalAlignment="Left" Margin="21,67,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="559">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn  Header="ID" Binding="{Binding ID}"></sdk:DataGridTextColumn>
                <!--<sdk:DataGridTextColumn  Header="Color" Binding="{Binding Path=color, Converter={StaticResource colorLocal}}" ></sdk:DataGridTextColumn>-->
                <sdk:DataGridTemplateColumn Header="Color">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
<Rectangle Height="10" HorizontalAlignment="Left" Margin="10,10,0,0" Name="rectangle1"
           Stroke="Black" StrokeThickness="1"
Fill="{Binding Path=color, Converter={StaticResource colorLocal}}"
          
           VerticalAlignment="Top" Width="20" />
                            <!--<sdk:Label Height="28" HorizontalAlignment="Left"
                                       Margin="10,10,0,0" Name="label1"
                                       VerticalAlignment="Top" Width="120"
                                       Content="colored text"
                                       Foreground="{Binding Path=color, Converter={StaticResource colorLocal}}" />-->
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="IValueConvertor for String to Color conversion and Binding in dataGrid" VerticalAlignment="top" FontSize="16"/>
    </Grid>
</navigation:Page>

colorconv.cs

Imports System
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Data
Namespace SilverlightApplication1
    Public Class colorconv
     Implements IValueConverter

        Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object
            Dim cc As String =  value as String
            String xamlString = "<Canvas xmlns=\"http:'schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+cc+"\"/>";
            Dim c As Canvas = CType(System.Windows.Markup.XamlReader.Load(xamlString), Canvas)
            Dim mistyRoseBrush As SolidColorBrush = CType(c.Background, SolidColorBrush)
            Dim mistyRose As Color =  mistyRoseBrush.Color
            Dim b As SolidColorBrush =  New SolidColorBrush(mistyRose)
            Return b'mistyRose;
          'Colors.
        End Function

        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object
            Throw New NotImplementedException()
        End Function
    End Class
End Namespace

ivalueconverter color converter in wpf

ivalueconverter color converter in wpf

Step1) Create a WPF Project
Step 2) Add a datagrid to XAML

Step 3) Add a class
      public class ColorDemo
    {
        public int ID { get; set; }
        public String color { get; set; }
    }

Step 4) Build data

 void BuildData()
        {
            listColor.Add(new ColorDemo { ID=1, color="red"});
            listColor.Add(new ColorDemo { ID = 2, color = "green" });
            listColor.Add(new ColorDemo { ID = 3, color = "blue" });

        }

Step 5) Add a class for Color Conversion

namespace SilverlightApplication1
{
    public class colorconv:IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter,                            System.Globalization.CultureInfo culture)
        {
            String cc = value as String;
            String xamlString = "<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+cc+"\"/>";
            Canvas c = (Canvas)System.Windows.Markup.XamlReader.Load(xamlString);
            SolidColorBrush mistyRoseBrush = (SolidColorBrush)c.Background;
            Color mistyRose = mistyRoseBrush.Color;
            SolidColorBrush b = new SolidColorBrush(mistyRose);
            return b;

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

Step 6)  Bind List data to dataGrid

void Bind()
        {
            dataGrid1.ItemsSource = listColor;
        }

Step 7) Run the Application
               Output:


Complete Source Code

Page1.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace SilverlightApplication1
{
    public partial class Page1 : Page
    {
        List<ColorDemo> listColor = new List<ColorDemo>();
        public Page1()
        {
            InitializeComponent();
            BuildData();
            Bind();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        void Bind()
        {
            dataGrid1.ItemsSource = listColor;
        }
        void BuildData()
        {
            listColor.Add(new ColorDemo { ID=1, color="red"});
            listColor.Add(new ColorDemo { ID = 2, color = "green" });
            listColor.Add(new ColorDemo { ID = 3, color = "blue" });

            Color c =  Color.FromArgb(255,255,255,0);
            //rectangle1.Fill = new SolidColorBrush(c);
        }
    }


    public class ColorDemo
    {
        public int ID { get; set; }
        public String color { get; set; }
    }
}

Page.xaml

<navigation:Page x:Class="SilverlightApplication1.Page1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
               
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page1 Page" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:sp="clr-namespace:SilverlightApplication1"
                 >
    <Grid x:Name="LayoutRoot">
        <Grid.Resources>
            <sp:colorconv x:Key="colorLocal"></sp:colorconv>
        </Grid.Resources>
            <sdk:DataGrid AutoGenerateColumns="False" Height="144" HorizontalAlignment="Left" Margin="21,67,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="559">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn  Header="ID" Binding="{Binding ID}"></sdk:DataGridTextColumn>
                <!--<sdk:DataGridTextColumn  Header="Color" Binding="{Binding Path=color, Converter={StaticResource colorLocal}}" ></sdk:DataGridTextColumn>-->
                <sdk:DataGridTemplateColumn Header="Color">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
<Rectangle Height="10" HorizontalAlignment="Left" Margin="10,10,0,0" Name="rectangle1"
           Stroke="Black" StrokeThickness="1"
Fill="{Binding Path=color, Converter={StaticResource colorLocal}}"
          
           VerticalAlignment="Top" Width="20" />
                            <!--<sdk:Label Height="28" HorizontalAlignment="Left"
                                       Margin="10,10,0,0" Name="label1"
                                       VerticalAlignment="Top" Width="120"
                                       Content="colored text"
                                       Foreground="{Binding Path=color, Converter={StaticResource colorLocal}}" />-->
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="IValueConvertor for String to Color conversion and Binding in dataGrid" VerticalAlignment="top" FontSize="16"/>
    </Grid>
</navigation:Page>

colorconv.cs


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
namespace SilverlightApplication1
{
    public class colorconv:IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            String cc = value as String;
            String xamlString = "<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+cc+"\"/>";
            Canvas c = (Canvas)System.Windows.Markup.XamlReader.Load(xamlString);
            SolidColorBrush mistyRoseBrush = (SolidColorBrush)c.Background;
            Color mistyRose = mistyRoseBrush.Color;
            SolidColorBrush b = new SolidColorBrush(mistyRose);
            return b;//mistyRose;
          //Colors.
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


Data Annotations in WPF VB.NET

Data Annotations in WPF VB.NET


Step1) Create WPF Project
Step2) Add 3 TextBoxes

  • Username
  • Password
  • Email

Step 3)  Add a custom class  called Profile
 
  public class Profile
    {
        [Required(ErrorMessage = "user name required", AllowEmptyStrings=false)]
        public String username { get; set; }
        [Required(ErrorMessage = "password required")]
        public String password { get; set; }
        [Required(ErrorMessage = "email required")]
        public String email { get; set; }
    }


Step 4) Bind these class  properties to TextBoxes in XAML.

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      mc:Ignorable="d"
      d:DesignHeight="400" d:DesignWidth="600" x:Class="Wpfone.ValidationPage"
     xmlns:local="clr-namespace:Wpfone"
    Title="ValidationPage" >
    <Page.Resources>
        <local:Profile x:Key="myprofile"></local:Profile>
    </Page.Resources>
    <Page.DataContext>
        <Binding  Source="{ StaticResource myprofile}"></Binding>
    </Page.DataContext>
    <Canvas x:Name="canvas1" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="700">
        <TextBlock TextWrapping="Wrap" Text="Validating Controls in WPF/Validations in WPF" FontSize="30px"/>
        <Label Content="UserName:" Canvas.Left="10" Canvas.Top="49" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtUsername" Text="{Binding Path=username}" Canvas.Left="130" Canvas.Top="54" Height="21" Width="242">
        </TextBox>
        <Label Content="Password:" Canvas.Left="10" Canvas.Top="87" Width="103"/>
        <TextBox  TextWrapping="Wrap" x:Name="txtPassword"  Canvas.Left="130" Canvas.Top="92" Height="21" Width="242">
            <TextBox.Text>
                <Binding  Path="password" Source="{StaticResource myprofile}" 
                          NotifyOnValidationError="True" 
                          ValidatesOnExceptions="True"
                            BindsDirectlyToSource="True"
                          ></Binding>
            </TextBox.Text>
        </TextBox>
        <Label Content="Email:" Canvas.Left="10" Canvas.Top="125" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtEmail" Text="{Binding Path=email}" Canvas.Left="130" Canvas.Top="130" Height="21" Width="242">
        </TextBox>
        <Button  x:Name="btnSubmit" Content="Submit" Width="106" Canvas.Left="38" Canvas.Top="183" Height="23" Click="btnSubmit_Click"/>
        <CheckBox Content="CheckBox"/>

    </Canvas>


</Page>

Step 5) in The Button Event Handler

Private  Sub btnSubmit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
           Me.InvalidateArrange()
            Dim p As Profile = CType(Me.DataContext, Profile)
            Dim context As ValidationContext =  New ValidationContext(p,serviceProvider:Nothing,items:Nothing)
           Dim list As var =  New List<System.ComponentModel.DataAnnotations.ValidationResult>()
           Dim b As Boolean =  Validator.TryValidateObject(p,context,list,True)
           Dim MessageBox.Show("Validation success") As if(b)
           else
           {
               Dim strErr As String = String.Empty
               Dim errResult As System.ComponentModel.DataAnnotations.ValidationResult
               For Each errResult In list
                   strErr += errResult.ErrorMessage
               Next
               MessageBox.Show(strErr)
           }
End Sub



Output


Tags:data annotations in wpf, data annotations validator , validations in WPF, field validations in WPF, data validations in WPF,Validations in WPF textbox,UI validations in WPF.

Data Annotations in WPF C#

data annotations in wpf


Step1) Create WPF Project
Step2) Add 3 TextBoxes
  • Username
  • Password
  • Email

Step 3)  Add a custom class  called Profile
   
  public class Profile
    {
        [Required(ErrorMessage = "user name required", AllowEmptyStrings=false)]
        public String username { get; set; }
        [Required(ErrorMessage = "password required")]
        public String password { get; set; }
        [Required(ErrorMessage = "email required")]
        public String email { get; set; }
    }


Step 4) Bind these class  properties to TextBoxes in XAML.

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      mc:Ignorable="d"
      d:DesignHeight="400" d:DesignWidth="600" x:Class="Wpfone.ValidationPage"
     xmlns:local="clr-namespace:Wpfone"
    Title="ValidationPage" >
    <Page.Resources>
        <local:Profile x:Key="myprofile"></local:Profile>
    </Page.Resources>
    <Page.DataContext>
        <Binding  Source="{ StaticResource myprofile}"></Binding>
    </Page.DataContext>
    <Canvas x:Name="canvas1" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="700">
        <TextBlock TextWrapping="Wrap" Text="Validating Controls in WPF/Validations in WPF" FontSize="30px"/>
        <Label Content="UserName:" Canvas.Left="10" Canvas.Top="49" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtUsername" Text="{Binding Path=username}" Canvas.Left="130" Canvas.Top="54" Height="21" Width="242">
        </TextBox>
        <Label Content="Password:" Canvas.Left="10" Canvas.Top="87" Width="103"/>
        <TextBox  TextWrapping="Wrap" x:Name="txtPassword"  Canvas.Left="130" Canvas.Top="92" Height="21" Width="242">
            <TextBox.Text>
                <Binding  Path="password" Source="{StaticResource myprofile}" 
                          NotifyOnValidationError="True" 
                          ValidatesOnExceptions="True"
                            BindsDirectlyToSource="True"
                          ></Binding>
            </TextBox.Text>
        </TextBox>
        <Label Content="Email:" Canvas.Left="10" Canvas.Top="125" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtEmail" Text="{Binding Path=email}" Canvas.Left="130" Canvas.Top="130" Height="21" Width="242">
        </TextBox>
        <Button  x:Name="btnSubmit" Content="Submit" Width="106" Canvas.Left="38" Canvas.Top="183" Height="23" Click="btnSubmit_Click"/>
        <CheckBox Content="CheckBox"/>

    </Canvas>


</Page>

Step 5) in The Button Event Handler
 private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
           this.InvalidateArrange();
            Profile p=(Profile)this.DataContext;
            ValidationContext context = new ValidationContext(p, serviceProvider:null,items:null);
           var list = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
           bool b= Validator.TryValidateObject(p, context, list, true);
           if (b) MessageBox.Show("Validation success");
           else
           {
               String strErr=String.Empty;
               foreach (System.ComponentModel.DataAnnotations.ValidationResult errResult in list)
               {
                   strErr += errResult.ErrorMessage;
               }
               MessageBox.Show(strErr);
           }
}

Output


Tags:data annotations in wpf, data annotations validator , validations in WPF, field validations in WPF, data validations in WPF,Validations in WPF textbox,UI validations in WPF.

















Sunday, 23 December 2012

Converting String to Color Object in WPF VB.NET


Converting String to Color Object in WPF VB.NET 


Dim myColor As String =  "Red"
            String xamlString = "<Canvas xmlns=\"http:'schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+myColor +"\"/>";

            Dim c As Canvas = CType(System.Windows.Markup.XamlReader.Load(xamlString), Canvas)
            Dim mistyRoseBrush As SolidColorBrush = CType(c.Background, SolidColorBrush)
            Dim backColor As Color =  mistyRoseBrush.Color

            Dim FinalBrush As SolidColorBrush =  New SolidColorBrush(backColor)


How do I convert a string value to a SolidColorBrush in WPFand C#


Converting String to Color Object in C# WPF


            String myColor = "Red";
            String xamlString = "<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\""+myColor +"\"/>";
            Canvas c = (Canvas)System.Windows.Markup.XamlReader.Load(xamlString);
            SolidColorBrush mistyRoseBrush = (SolidColorBrush)c.Background;
            Color backColor = mistyRoseBrush.Color;
            
            SolidColorBrush FinalBrush = new SolidColorBrush(backColor );