Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Sunday, January 31, 2010

Custom GroupBox Control for Silverlight 3

In previous post i put xaml that allow to create GroupBox using XAML.

Here i am adding custom groupbox control.

image

Download link :   GroupBox control for Silverlight 3

Codeplex Link :  Silverlight3 GroupBox

GroupBox control for Silverlight3

GroupBox control is not available in Silverlight 3, but you can create GroupBox control using following XAML.

<Border CornerRadius="10" Background="AliceBlue" BorderBrush="Black" BorderThickness="1" Margin="10,10,10,10" Width="400" x:Name="Test">
            <StackPanel>
                <Border Margin="20,-10,0,0" Background="AliceBlue" HorizontalAlignment="Left">
                    <TextBlock Text="User Setting" Margin="10,0,10,0" FontWeight="Bold"></TextBlock>
                </Border>
              <!-- Put your content -->
            </StackPanel>
        </Border>
In above XAML you can replace <!-- Put your content –> with your data inside groupbox .

For Example :

<StackPanel>
            <TextBox>
</StackPanel>

Let me know your comment on this.

Saturday, January 16, 2010

Silverlight 3: Programmatically Validate Textbox

In previous post about validation in Silverlight, I explained the How binding is used to validate data ? .

Here i am going to explain how to validate Textbox ( Any control that has validation states group).

There are three validation states. 1. Valid 2. InvalidFocused 3. InvalidUnfocused. Now use VisualStateManager to change the state of control. Here is common method.

public void SetState(Control c, string message,string state)     
{
if (state == "Invalid")
{
if (c.Focus())
VisualStateManager.GoToState(c, "InvalidFocused", false);
else
VisualStateManager.GoToState(c, "InvalidUnfocused", false); ToolTip tp = ((Grid)VisualTreeHelper.GetChild(c, 0)).FindName("validationTooltip") as ToolTip;
tp.DataContext = message;
tp.Template = LayoutRoot.Resources["ValidationToolTipTemplate"] as ControlTemplate;
}
else
{
VisualStateManager.GoToState(c, "Valid", false);
}
}

In XAML Page you have to specify control template.

<ControlTemplate x:Key="ValidationToolTipTemplate">
<Grid x:Name="Root" >
<Border Margin="4,4,-4,-4" Background="#152A2E31" CornerRadius="4"/>
<Border Margin="3,3,-3,-3" Background="#252A2E31" CornerRadius="4"/>
<Border Margin="2,2,-2,-2" Background="#352A2E31" CornerRadius="4"/>
<Border Margin="1,1,-1,-1" Background="#452A2E31" CornerRadius="4"/>
<Border Background="#FFDC000C" CornerRadius="4"/>
<Border CornerRadius="4">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#66FFFFFF"/>
<GradientStop Color="#66000000" Offset="1"/>
<GradientStop Color="#00E5E5E5" Offset="0.1"/>
<GradientStop Color="#00161616" Offset="0.9"/>
</LinearGradientBrush>
</Border.Background>
<TextBlock Margin="8,3,8,4" MaxWidth="250" UseLayoutRounding="false" Foreground="White" Text="{Binding}" TextWrapping="Wrap"/>
</Border>
</Grid>
</ControlTemplate>

This control template is used for validation tooltip.

Control like Textbox,listbox ,combobox,checkbox has validation states so you can use this method.

Example:

if(txtFirstName.Text == “”)
{
SetState(txtFirstName , “Invalid”, “Please enter first name”);
}

Let me know you comment on this.

Wednesday, December 9, 2009

Silverlight 3 : Enable and Disable Validation For Control.

Please check previous post about validation with silverlight.

Enable and Disable Validation or you can say manually adding and remove binding for control.

In previous post i bound myName TextBox to Name property of Customer, But some case you do not want to validate that control and to do so you need to clear binding. ( Simplest way as per my thinking).

1. Remove Binding in Silverlight or Disable Validation

// Clear all errors from validation summary. ( Review previous post XAML)

valida.Errors.Clear();

// Set Text to clear ( As per your need )
myName.Text = String.Empty;

//This call will cleae binding for TextProperty( Take any dependency property)
myName.SetValue(TextBox.TextProperty, DependencyProperty.UnsetValue);
            myName.ClearValue(TextBox.TextProperty);

2. Adding Binding in Silverlight or Enable Validation.

Binding binding = new Binding("Name");
           binding.ValidatesOnExceptions = true;
           binding.NotifyOnValidationError = true;
           binding.Mode = BindingMode.TwoWay;
           myName.SetBinding(TextBox.TextProperty, binding);


Let me know your comment on this.

Silverlight 3 : Validation

To do validation in silverlight 3 , need to use dataannotation. In my previous post i discussed about binding and resource file.

1. Sample XAML File.

<UserControl xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"  xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"  x:Class="SilverlightApplication2.MainPage"    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication2.Resourses" xmlns:localCustom="clr-namespace:SilverlightApplication2"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <local:Strings x:Key="LocStrings"></local:Strings>
        <localCustom:DisplayLabelConvertor x:Key="display"></localCustom:DisplayLabelConvertor>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="#FF333333">     
        <StackPanel Orientation="Vertical" x:Name="MyDataForm" BindingValidationError="MyDataForm_BindingValidationError" >
            <dataInput:ValidationSummary x:Name="valida" Height="100"></dataInput:ValidationSummary>     

            <TextBox x:Name="myName" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" >
            </TextBox>         
                <Button Content="save" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</UserControl>

2. CS File.

public partial class MainPage : UserControl
    {
        Customer c = new Customer();
        private int _errorCount = 0;
        public MainPage()
        {
            InitializeComponent();       
            MyDataForm.DataContext = c;
        }

        private void MyDataForm_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }     

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _errorCount = 0;

            // Need to do for validating control.
            // If you do not do this then untill you make any change in control no validation will work.
            // Like form first time open and you prees submit then it will not validate . To do so this is required.
            BindingExpression exp = myName.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            exp.UpdateSource();

            if (_errorCount ==0)
            {
                //Success
            }
            else
            {
                //Error
            }
        }

    }

3. Enjoy Validation………… :)

Let me know your comment.

Sunday, December 6, 2009

Silverlight 3 and Resource File

In silverlight you can access resource file to customize label and other data that need to be localize.

1. Create class that use DataAnnotation attributes.

public class Customer
   {
       private string _name = string.Empty;
       [Display(ResourceType=typeof(SilverlightApplication2.Resourses.Strings),Name="CustomerLabel")]
       [Required(ErrorMessageResourceType = typeof(SilverlightApplication2.Resourses.Strings), ErrorMessageResourceName = "CustomerNameError")]
       public string Name
       {
           get
           {
               return _name;
           }
           set
           {
               Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name" });               
               _name = value;
           }
       }
   }

In above class you can see that for Display and Required attribute , ResourceType and ErrorMessageResourceType set. This will point to resource file. Also in setter of property you have to validate the value.

2. Add resource file as per your need. For example here i added Strings.Resx file.

Step 3 is very very important in order to access resource in .xap file.

3. Specially for Silverlight open Strings.Resx.cs file. Change access modifier from internal to public. Also set public for each resource string. ( See below images.)

image

image

Generate another resource file for different culture. For example fr-CA culture you need to generate Strings.fr-CA.resx.

4. Now in silverlight application if you use DataForm then just need to do following.This will automatic use label from display resource.

dfCustomer.CurrentItem = new Customer();

5. To access resource in XAML.

<UserControl xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"  xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"  x:Class="SilverlightApplication2.MainPage"
    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"
    xmlns:local="clr-namespace:SilverlightApplication2.Resourses" xmlns:localCustom="clr-namespace:SilverlightApplication2"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <local:Strings x:Key="LocStrings"></local:Strings>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="#FF333333">     
        <StackPanel Orientation="Vertical" x:Name="MyDataForm" >
            <dataInput:ValidationSummary Height="100"></dataInput:ValidationSummary>          
            <TextBox Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" >
            </TextBox>
            <Button Content="save" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</UserControl>

In cs file.

public MainPage()
       {

           InitializeComponent();        
           Customer c = new Customer();
           c.Name = "TEST";
           MyDataForm.DataContext = c;
       }

 

6. Last step but very important. You have to edit .csproject file in notepad. Add supportedcultures.

<SupportedCultures>fr-CA
</SupportedCultures>

Let me know update or any other idea about resource file.