Wednesday, November 30, 2011

Thursday, July 21, 2011

WPF Adorn Control With User Controls

Adorner

Adorner is an extension to a UI element in WPF. WPF controls have an extra layer called AdornerLayer associated with it. We can add adorners or the decorators to this layer and display to the user in response to any event. Adorner can be a new custom control; can be template; or just a drawing over the current control
For our sample, I am using an adorner which will draw a rectangle and text.

Sample Adorner

Create an adorner class inherited from Adorner. Override the OnRender method for drawing the shapes and text. We can get access to the element that this adorner is bound to by using the AdornedElement property.  
In our sample, I defined a Brush and Pen for drawing the rectangle and text.  For drawing the rectangle, used the AdornerElement’s size.
public class MyAdorner : Adorner
    {
        public MyAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
        }
        protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
        {
            SolidColorBrush renderBrush=new SolidColorBrush(Colors.LightCoral);
            Pen renderPen= new Pen(new SolidColorBrush(Colors.DarkBlue), 1.0);
            drawingContext.DrawRectangle(renderBrush, renderPen,
                new Rect(new Point(0, 0), AdornedElement.DesiredSize));
            drawingContext.DrawText(new FormattedText("Help Text!", new CultureInfo("en-US"), FlowDirection.LeftToRight, new Typeface("Arial"), 18, Brushes.Black),
               new Point(10,10));
        }
    }


User Control

For our sample, I have a small UserControl contains one Button.
 
<UserControl x:Class="WpfControlLibrary1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             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="41" d:DesignWidth="102" FontSize="16" MouseEnter="UserControl_MouseEnter" MouseLeave="UserControl_MouseLeave">
    <Grid Height="39" Width="98">
        <Button Content="Hello !" Height="35" HorizontalAlignment="Left" Margin="0,4,0,0" Name="button1" VerticalAlignment="Top" Width="98"
                 FontWeight="Bold" FontSize="18" Foreground="#FF7A0000" />
    </Grid>
</UserControl>

On UserControl’s MouseEnter event, created the Adorner for the button and add the same to the button’s AdornerLayer.
private void UserControl_MouseEnter(object sender, MouseEventArgs e)
        {
            MyAdorner ad = new MyAdorner(button1);
            AdornerLayer adLayer = AdornerLayer.GetAdornerLayer(button1);
            adLayer.Add(ad);
        }
On UserControl’s MouseLeave event, find all the adorners associated with the button and remove our custom adorner. We can have multiple adorners associated with a UI element.
 
        
private void UserControl_MouseLeave(object sender, MouseEventArgs e)
        {
            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(button1);
            if (adornerLayer != null)
            {
                Adorner[] adorners = adornerLayer.GetAdorners(button1);
                if (adorners != null)
                {
                    foreach (Adorner adorner in adorners)
                    {
                        if (typeof(MyAdorner).IsAssignableFrom(adorner.GetType()))
                        {
                            adornerLayer.Remove(adorner);
                        }
                    }
                }
            }
        }


WPF Application

Create a WPF application and drag and drop our UserControl. Execute the application and observe the adorner displayed on Mouse enter event of UserControl.


 
When the mouse pointer is over the UserControl, adorner gets added to the AdornerLayer of the button.

http://www.dotnetfunda.com/articles/article1201-wpf-adorner-.aspx

User Control in WPF

Using the Code

There we go. First we should create a User Control. Thus we have to select WPF User Control Library Project.
Custom User Control in WPF Now, we can create or edit the XAML code for creating a custom user control. I've used this XAML code for a custom tooltip. It's up to you what you want.
<UserControl 
    Name="UserControlToolTip"
    x:Class="CustomToolTip.UserControl1"
    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" RenderTransformOrigin="0,0" HorizontalAlignment="Left" 
 VerticalAlignment="Top" >
    
    <UserControl.RenderTransform>
        <TransformGroup>
            <ScaleTransform ScaleX="1" ScaleY="1"/>
            <SkewTransform AngleX="0" AngleY="0"/>
            <RotateTransform Angle="0"/>
            <TranslateTransform x:Name="UserControlToolTipXY" X="0" Y="0"/>
        </TransformGroup>
    </UserControl.RenderTransform>
    
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center" 
 MinWidth="200" MinHeight="120">
     <Grid.RowDefinitions>
      <RowDefinition Height="0.333*"/>
      <RowDefinition Height="0.667*"/>
     </Grid.RowDefinitions>
        <Rectangle Fill="#FFFBFBFB" Stroke="#FF000000" RadiusX="10" RadiusY="10"
          RenderTransformOrigin="0.139,0.012" StrokeThickness="1" Grid.RowSpan="2">
            <Rectangle.BitmapEffect>
                <DropShadowBitmapEffect Opacity="0.8"/>
            </Rectangle.BitmapEffect>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.139,0.012" 
         StrokeThickness="10" Stroke="{x:Null}" 
 Margin="1,1,1,1" Grid.Row="0" Grid.RowSpan="2">
         <Rectangle.Fill>
          <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0.725">
           <GradientStop Color="#00E6D9AA" Offset="0.487"/>
           <GradientStop Color="#FFE6D9AA" Offset="0.996"/>
          </LinearGradientBrush>
         </Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
         StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
         <Rectangle.Fill>
          <LinearGradientBrush EndPoint="0.014,0.5" StartPoint="0.211,0.5">
           <GradientStop Color="#00E6D9AA" Offset="0.513"/>
           <GradientStop Color="#FFE6D9AA" Offset="0.996"/>
          </LinearGradientBrush>
         </Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
         StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
         <Rectangle.Fill>
          <LinearGradientBrush EndPoint="0.493,0.002" StartPoint="0.493,0.33">
           <GradientStop Color="#00E6D9AA" Offset="0.513"/>
           <GradientStop Color="#FFE6D9AA" Offset="0.996"/>
          </LinearGradientBrush>
         </Rectangle.Fill>
        </Rectangle>
        <Rectangle RadiusX="10" RadiusY="10" RenderTransformOrigin="0.493,0.485" 
         StrokeThickness="10" Stroke="{x:Null}" Grid.RowSpan="2" Margin="1,1,1,1">
         <Rectangle.Fill>
          <LinearGradientBrush EndPoint="0.99,0.441" StartPoint="0.794,0.441">
           <GradientStop Color="#00E6D9AA" Offset="0.513"/>
           <GradientStop Color="#FFE6D9AA" Offset="0.996"/>
          </LinearGradientBrush>
         </Rectangle.Fill>
        </Rectangle>
        <TextBlock Text="TextBlock" TextWrapping="Wrap" x:Name="TextBlockToolTip" 
         RenderTransformOrigin="0.5,0.5" Grid.Row="1" HorizontalAlignment="Left" 
             VerticalAlignment="Center" Margin="20,0,0,20" />
        <TextBlock Name="ToolTipTitle" HorizontalAlignment="Stretch" Margin="15,16,15,6.1" 
         FontSize="14" Text="title" d:LayoutOverrides="Height" />
    </Grid>
</UserControl>
Also, I've added these methods and properties for controlling the elements:
namespace CustomToolTip
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        public double UserControlToolTipX
        {
            get { return this.UserControlToolTipXY.X; }
            set { this.UserControlToolTipXY.X = value; }
        }

        public double UserControlToolTipY
        {
            get { return this.UserControlToolTipXY.Y; }
            set { this.UserControlToolTipXY.Y = value; }
        }

        public string UserControlTextBlockToolTip
        {
            get { return TextBlockToolTip.Text; }
            set { TextBlockToolTip.Text = value; }
        }

        public string UserControlToolTipTitle
        {
            get { return ToolTipTitle.Text; }
            set { ToolTipTitle.Text = value; }
        }
    }
}
After that, press Shift + F6 for building the DLL file. Now we can create a WPF application and use our custom user control in it. Thus, we should choose a WPF Application Project.
WPF APP Then, we have to add our User Control DLL file in the references.

We are going to use the custom User Control within a XAML window. So we have to add an extra XAML code. We have to add the following line within Window element:
user control XAML At last, we must have a Window tag in our XAML code like this:
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myToolTip="clr-namespace:CustomToolTip;assembly=CustomToolTip"
    Title="Window1" Height="600" Width="800">
</Window>
OK, now we can use the User Control in the XAML code with XAML code like this:
user control XAML At last, I've created this XAML code:
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myToolTip="clr-namespace:CustomToolTip;assembly=CustomToolTip"
    Title="Window1" Height="600" Width="800">
    <Grid x:Name="rootGrid" RenderTransformOrigin="0.5,0.5">
     <Grid.RenderTransform>
      <TransformGroup>
       <ScaleTransform ScaleX="1" ScaleY="1"/>
       <SkewTransform AngleX="0" AngleY="0"/>
       <RotateTransform Angle="0"/>
       <TranslateTransform x:Name="rootGridXY" X="0" Y="0"/>
      </TransformGroup>
     </Grid.RenderTransform>
        <Rectangle Margin="26,34,496,374" Name="rectangle1" Stroke="Black" 
                   Fill="Coral" MouseLeave="rectangle_MouseLeave" 
  MouseMove="rectangle_MouseMove" />
        <Rectangle Fill="Lavender" Margin="537,29,53,376" Name="rectangle2" 
                   Stroke="Black" MouseMove="rectangle_MouseMove" 
  MouseLeave="rectangle_MouseLeave" />
        <Rectangle Fill="Peru" Margin="192,391,186,37.995" Name="rectangle3" 
                   Stroke="Black" MouseMove="rectangle_MouseMove" 
  MouseLeave="rectangle_MouseLeave" />
        <myToolTip:UserControl1 UserControlTextBlockToolTip="Some texts" 
                                UserControlToolTipTitle="Title" 
                                Visibility="Hidden" 
                                x:Name="customToolTip" />
    </Grid>
</Window>
And these are the methods for showing or hiding our custom ToolTip:
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void rectangle_MouseLeave(object sender, MouseEventArgs e)
        {
            state = true;
            customToolTip.Visibility = Visibility.Hidden;
        }

        bool state = true;
        Random rand = new Random(DateTime.Now.Millisecond);

        private void rectangle_MouseMove(object sender, MouseEventArgs e)
        {
            if (state)
            {
                customToolTip.Visibility = Visibility.Visible;
                customToolTip.UserControlToolTipTitle = 
   (sender as Rectangle).Name.ToUpperInvariant();
                customToolTip.UserControlTextBlockToolTip = "";
                for (int i = 0; i < rand.Next(1, 30); i++)
                    customToolTip.UserControlTextBlockToolTip += (sender as Rectangle).Name 
                     + "\t" + i.ToString() + "\n";
            }
            customToolTip.UserControlToolTipX = Mouse.GetPosition(this).X + 10;
            customToolTip.UserControlToolTipY = Mouse.GetPosition(this).Y + 10;
            state = false;
        }
    }
}
That's all.

Out Put

preview

http://www.codeproject.com/KB/WPF/UserControl.aspx

Saturday, June 18, 2011

Passing Data Between Forms


Sample Image - PassData.jpg
Passing Data Between Forms

Introduction

Some of you would have faced a scenario where you wanted to pass data from one form to another in WinForms. Honestly, I too had a similar problem (that’s why I am writing this article!).
There are so many methods (How many? I don't know) to pass data between forms in Windows application. In this article, let me take four important (easiest) ways of accomplishing this:
  1. Using constructor
  2. Using objects
  3. Using properties
  4. Using delegates
Let us see all the above methods in detail in the following sections.
For data to be passed between forms using any of the above methods, we need two forms and some controls. Let us start by following the steps given below.

Step 1

Create a new project and select Windows application. This will create a default form as “Form1”. We can use this form for sending data.

Step 2

Add a textbox and a button to the form.

Step 3

Add another Windows Form for receiving the data and to display it. Right click the project and select Add->Add Windows Form. Enter a name or use the default name “Form2.cs” and click ok button.

Step 4

Add a label to the second form to display the text from form1.

The Constructor Approach

This could be the easiest method of all. A method is invoked whenever you instantiate an object. This method is called a constructor. Code a constructor for form2 class with one string parameter. In the constructor, assign the text to the label’s text property. Instantiate form2 class in form1’s button click event handler using the constructor with one string parameter and pass the textbox’s text to the constructor.
Follow the steps given below:

Step 1

Code a constructor for form2 class as below:
Collapse
public Form2(string strTextBox)
{
  InitializeComponent(); 
  label1.Text=strTextBox;
}

Step 2

Instantiate form2 class in form1’s button click event handler as below:
Collapse
private void button1_Click(object sender, System.EventArgs e)
{
    Form2 frm=new Form2(textBox1.Text);
    frm.Show();
}

The Object Approach

Objects are reference types, and are created on the heap, using the keyword new. Here we are going to pass data using objects. The approach is simple; in form2 we are going to instantiate form1 class.
Then instantiate form2 in the button click event handler of form1. After this we are going to pass form1 object to the form2 using form2’s form1 object. The last step is to invoke the form2 window by calling the form2’s show method.
Follow the below steps:

Step 1

Change the access modifier for textbox in form1 to public:
Collapse
public class Form1 : System.Windows.Forms.Form
{  
 public System.Windows.Forms.TextBox textBox1;

Step 2

In the button click event-handler, add the following code:
Collapse
private void btnSend_Click(object sender, System.EventArgs e)
{
    Form2 frm= new Form2();
    frm.frm1=this;
    frm.Show();
}

Step 3

In form2.cs, instantiate form1 class:
Collapse
public class Form2 : System.Windows.Forms.Form
{
     private System.Windows.Forms.Label label1;
     public Form1 frm1;

Step 4

In Form2’s Load method, type cast the object (frm1) of form1 to Form1 and access form1’s textbox and assign its text to label’s text.
Collapse
private void Form2_Load(object sender, System.EventArgs e)
{
    label1.Text=((Form1)frm1).textBox1.Text;
}

The Properties Approach

Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. In this method, we are going to add one property to each form. In form1 we are going to use one property for retrieving value from the textbox and in form2, one property to set the label’s text property. Then, in form1’s button click event handler, we are going to instantiate form2 and use the form2’s property to set the label’s text.
Follow the below steps:

Step 1

Add a property in form1 to retrieve value from textbox:
Collapse
public string _textBox1
{
    get{return textBox1.Text;}
}

Step 2

Add a property in form2 to set the labels’ text:
Collapse
public string _textBox
{
   set{label1.Text=value;}
}

Step 3

In form1’s button click event handler, add the following code:
Collapse
private void button1_Click(object sender, System.EventArgs e)
{
     Form2 frm=new Form2();
     frm._textBox=_textBox1;
     frm.Show();
}

The Delegates Approach

Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type. You can encapsulate any matching method in that delegate. Here we are going to create a delegate with some signature and assign a function to the delegate to assign the text from textbox to label.
Follow the below steps:

Step 1

Add a delegate signature to form1 as below:
Collapse
public delegate void delPassData(TextBox text);

Step 2

In form1’s button click event handler, instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below:
Collapse
private void btnSend_Click(object sender, System.EventArgs e)
{
    Form2 frm= new Form2();
    delPassData del=new delPassData(frm.funData);
    del(this.textBox1);
    frm.Show();
}

Step 3

In form2, add a function to which the delegate should point to. This function will assign textbox’s text to the label:
Collapse
public void funData(TextBox txtForm1)
{
    label1.Text = txtForm1.Text;
}