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

LayOuts in WPF

WPF Layouts spread in to five different types. They are Canvas,StackPanel,Wrappanel,Dockpanel and Grid. All layouts are fit for the specific requirements. Read the below Details for getting clear picture for different layouts.

Canvas Layout.
        This layout is used for designing the page based on the available space and Control angles. You can define the position based on Canvas properties like Left, Right etc. The another important(useful) property is Panel.ZIndex .It is used for aligning the Controls to top position.

 
       <Canvas>
            <Button Panel.ZIndex="1" Canvas.Left="10" Content="One">
            <Button Canvas.Left="10" Content="One"></Button>
            <Button Canvas.Right="10" Content="Two"></Button>
            <Button Canvas.Left="10" Canvas.Bottom="10" Content="Three"></Button>
            <Button Canvas.Right="10" Canvas.Bottom="10" Content="Four"></Button>
        </Canvas>

StackPanel Layout
       This layout is used for arranging the control in an equally fit in the available space. We align the control Horizontal or Vertical using Orientation

<StackPanel Orientation="Horizontal">
     <GroupBox >
        <Button Content="test"></Button>
     </GroupBox>
     <GroupBox  Background="Beige">
        <Button Content="test" Style="{StaticResource DialogButtonStyle}"></Button>
     </GroupBox>
     <GroupBox  Style="{StaticResource gdbox}">
        <Button Content="test"></Button>
     </GroupBox>
</StackPanel>

 
Wrap Panel Layout
       This layout is similar to the StackPanel ,the difference is it will not fill based on the available Space and it will automatically wrap to next line when control reach the last line.

<WrapPanel Orientation="Horizontal">
            <Button>0009090909</Button>
            <Button>000909090900909090999</Button>
            <Button>00090909090090909099999999999999999999</Button>
            <Button>00090909090090909099999999999999999999</Button>
</WrapPanel>

Dock Panel layout
                This layout is used for aligning the controls based on the positions like Left,right,Bottom & Top. Once we are not given any position it will fill the remaining area.

<DockPanel >
            <Button DockPanel.Dock="Right">1</Button>
            <Button DockPanel.Dock="Left">2</Button>
            <TextBox DockPanel.Dock="Top">test</TextBox>
            <TextBox DockPanel.Dock="Bottom">test2</TextBox>            <Button>22222222</Button>
        </DockPanel>

Grid Layout
       This layout very important and widely used one. This layout is similar to HTML table. The implementation is completely based on rows and columns.

<Grid>
    <Grid.RowDefinitions>
       <RowDefinition Height="0.878*"/>
       <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
       <ColumnDefinition Width="auto"></ColumnDefinition>
    </Grid.ColumnDefinitions>
<StackPanel Grid.RowSpan="2">
    <DataGrid x:Name="dg1" ItemsSource="{Binding People}" CanUserAddRows="False" HorizontalAlignment="Left"/>
   <TextBlock FontWeight="Bold" Margin="5" Text="The TestText property says '"><Run Text="{Binding TestText}"/><Run Text="'"/></TextBlock>
  <Button Content="Change Text" Command="{Binding ChangeTextCommand}" CommandParameter="{Binding SelectedItem, ElementName=dg1}"/>
</StackPanel>
</Grid>

 --Happy Doing

Creates a binding programmatically

 We can set Binding values through programmatically.We can set the source (value) to today’s date and then linked the binding to the txtBoundProgrammatically text box.
 
//Creates a binding programmatically
public void CreateBinding_programmatically()
{
//Creates a binding programmatically
Binding NewBinding = new Binding("Now");
NewBinding.Source = System.DateTime.Now;
NewBinding.Mode = BindingMode.OneWay;
txtBoundProgrammatically.SetBinding(TextBox.TextProperty, NewBinding);
}

Passing Parameters into Silverlight

There are a number of different methods for passing parameters into Silverlight:

o     Query string
o     InitParams property
o     JavaScript function calls
 
InitParams

The easiest way to pass parameters into a Silverlight application is with the InitParams property on the Silverlight control. Values passed in using this method need to be represented in the format Name=Value and separated by commas.
 
For example:

Name=Alex,Age=28,Country=Australia
To use the IntitParams property, just add params to the object tag like so:
<param name="InitParams" value="name=alex,sex=male" />
Input values can then be retrieved by iterating through the InitParams keys collection in

App.xaml.cs:

 //Initialization parameters.
foreach (String key in e.InitParams.Keys)
{
string strKey = key;
string strValue=e.InitParams[key];
}

Query String

Another method of passing parameters to a Silverlight is with the query string. The following code shows you how to iterate through all the query string values:

 //URL Params
foreach (String key in System.Windows.Browser.HtmlPage.Document.QueryString.Keys)
{
string KeyName = key;
string strValue=System.Windows.Browser.HtmlPage.Document.QueryString[key];
}

PopUp User control using silverlight


One of my requirement in Silverlight I need to create user control with a rich textbox and a button. The requirement is when click the button a popup should open with the content of text. We need to maintain the styles of text box in the popup also. That is the reason I have used Rich text control .
Xaml Code

<StackPanel Orientation="Horizontal" Grid.Row="0" HorizontalAlignment="Left">                <telerik:RadRichTextBox x:Name="_richTextBox" MaxWidth="280" DocumentInheritsDefaultStyleSettings="True" DocumentContentChanged="_richTextBox_DocumentContentChanged">                    <telerik:RadRichTextBox.Resources>
<documentsHtml:HtmlDataProvider x:Key="HtmlDataProvider" RichTextBox="{Binding ElementName=_richTextBox}" />  </telerik:RadRichTextBox.Resources>                </telerik:RadRichTextBox>
<Button Name="EllipsisCopyArt" Click="EllipsisCopyArt_Click" Tag="{Binding ElementName=_richTextBox}"   Content="..." Width="17" /> </StackPanel>

The above code I have used Telerik controls, we can use normal richtextbox or text box. For getting data from UI I have added a Dependency Property to the control and add one Property for reading the Value.
        public static readonly DependencyProperty RichTextProperty =
            DependencyProperty.Register("RichText", typeof(object), typeof(CustomRadRichTextBox), new PropertyMetadata(""));

public object RichText
        {
            get
            {
                return (object)GetValue(RichTextProperty);
            }
            set
           {
                SetValue(RichTextProperty, value);
           }
        }
When you click on the button the event is handled in the event handler .Inside we can create a new custom dialog class

private void EllipsisCopyArt_Click(object sender, RoutedEventArgs e)
        {
            if (RichText == null || RichText.ToString().Trim().Length == 0) return;
            Dialog dlg = new MyDialog();
            dlg.Controltext = RichText;
            dlg.Show(DialogStyle.ModalDimmed);
        }
Implementation of Dialog class

public abstract class Dialog
    {

        private bool _isShowing;
        private Popup _popup;
        private Grid _grid;
        private Canvas _canvas;
        private FrameworkElement _content;
        public void Show(DialogStyle style)
        {
            if (_isShowing)
                throw new InvalidOperationException();
            _isShowing = true;
           EnsurePopup(style);
            _popup.IsOpen = true;
            Application.Current.Host.Content.Resized += OnPluginSizeChanged;
        }
        public object Controltext = string.Empty;
        public void Close()
        {
            _isShowing = false;
            if (_popup != null)
            {
                _popup.IsOpen = false;
                Application.Current.Host.Content.Resized -= OnPluginSizeChanged;
            }
        }
        // Override this method to add your content to the dialog
        protected abstract FrameworkElement GetContent();
        private void EnsurePopup(DialogStyle style)
        {
            if (_popup != null)
                return;
            _popup = new Popup();
           _grid = new Grid();
            _popup.Child = _grid;
            if (style != DialogStyle.NonModal)
            {
                _canvas = new Canvas();
                if (style == DialogStyle.Modal)
                {
                    _canvas.Background = new SolidColorBrush(Colors.Transparent);
                }
                else if (style == DialogStyle.ModalDimmed)
                {
             _canvas.Background = new SolidColorBrush(Color.FromArgb(180, 180, 180, 180));
                }
                _grid.Children.Add(_canvas);
            }
            _grid.Children.Add(_content = GetContent());
            UpdateSize();
        }
 
        private void OnPluginSizeChanged(object sender, EventArgs e)
        {
            UpdateSize();
        }
        private void UpdateSize()
        {
            _grid.Width = Application.Current.Host.Content.ActualWidth;
            _grid.Height = Application.Current.Host.Content.ActualHeight;
            if (_canvas != null)
            {
                int width = int.Parse(HtmlPage.Window.Eval("screen.width").ToString());
                int height = int.Parse(HtmlPage.Window.Eval("screen.height").ToString());
                _canvas.Width = width;
                _canvas.Height = height;
            }
        }
    }

//Create enumeration for different styles.
    public enum DialogStyle
    {
        NonModal,
        Modal,
        ModalDimmed
    };
Finally we need to derive the Dialog class in to SubDialog class and implement the content or the Popup.We can able to load Template for this .
    public class MyDialog : Dialog
    {
        protected override FrameworkElement GetContent()
       {
            // You could just use Template for loading controls.
            Grid grid = new Grid() { Width = 360, MaxHeight = 415 };
            Border border = new Border() { BorderBrush = new SolidColorBrush(Colors.DarkGray), BorderThickness = new Thickness(5), Margin = new Thickness(0), Background = new SolidColorBrush(Colors.White) };
            Telerik.Windows.Documents.Model.Paragraph prgParagraph = new Telerik.Windows.Documents.Model.Paragraph();

            // create some text, and add it to the paragraph
            Telerik.Windows.Documents.Model.Span rnMyText = new Telerik.Windows.Documents.Model.Span(Convert.ToString(Controltext));

            prgParagraph.Inlines.Add(rnMyText);
            //Create new document
            Telerik.Windows.Documents.Model.RadDocument rd = new Telerik.Windows.Documents.Model.RadDocument();
            //Add new sections to Documents
            Telerik.Windows.Documents.Model.Section sec = new Telerik.Windows.Documents.Model.Section();
            sec.Blocks.Add(prgParagraph);
            rd.Sections.Add(sec);
            //Initialize Richtext box
            Telerik.Windows.Controls.RadRichTextBox _radRichTxtbox = new RadRichTextBox();
            _radRichTxtbox.Document = rd;
            _radRichTxtbox.KeyDown += new KeyEventHandler(_radRichTxtbox_KeyDown);
            _radRichTxtbox.MaxHeight = 400;
            _radRichTxtbox.MaxWidth = 310;
_radRichTxtbox.VerticalScrollBarVisibility =
System.Windows.Controls.ScrollBarVisibility.Auto;
            _radRichTxtbox.IsSpellCheckingEnabled = false;
            _radRichTxtbox.BorderThickness = new System.Windows.Thickness(0);
            _radRichTxtbox.IsReadOnly = true;
            _radRichTxtbox.IsSelectionMiniToolBarEnabled = false;
            Telerik.Windows.Documents.FormatProviders.Html.HtmlDataProvider _htmlDataProvider =
new Telerik.Windows.Documents.FormatProviders.Html.HtmlDataProvider();

            _htmlDataProvider.RichTextBox = _radRichTxtbox;
            _htmlDataProvider.Html = Controltext.ToString();
            _radRichTxtbox.Resources.Add("HtmlDataProvider", _htmlDataProvider);
            _radRichTxtbox.UpdateLayout();
            _radRichTxtbox.Margin = new System.Windows.Thickness(0, 0, 2, 0);
            Grid grid1 = new Grid();
            grid1.Margin = new System.Windows.Thickness(1);
            LinearGradientBrush brush = new LinearGradientBrush();
            brush.StartPoint = new Point(0, 0);
            brush.EndPoint = new Point(1, 3);
            brush.GradientStops.Add(new GradientStop { Color = ((Color)(Colors.Gray)), Offset = 0.4 });
            grid1.Background = brush;
            grid1.Children.Add(_radRichTxtbox);
            Button button = new Button() { Width = 20, Background = new SolidColorBrush Colors.Gray), Height = 24, Content = "X",
BorderBrush = new SolidColorBrush(Colors.Black),
BorderThickness = new Thickness(1),
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(2) };
grid1.Children.Add(button);
grid.Children.Add(border);
grid.Children.Add(grid1);
button.Click += (sender, args) => { Close(); };
return grid;
        }
       //Used for handelling Close button event
        void _radRichTxtbox_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }
    }
The popup will display with close button . It will help to close the popup.
 _canvas.Background = new SolidColorBrush(Color.FromArgb(180, 180, 180, 180));
The above code will used for making glass effect for the back ground of popup.