European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European Silverlight Hosting - HostForLIFE.eu :: PopUp Control In Silverlight

clock April 17, 2020 07:20 by author Peter

Pop Up Control is a Visual Prompt Control provided in Silverlight. There are certain times when you need to really grab the user's attention. Maybe you need to display details about a critical error. Then you can just use this control. This visual prompt is designed to simulate a dialog box.
In our Sample Application we will just demonstrate how to use it.

Create a Silverlight Project

Figure 1.1 Creating Silverlight Project


Designing the Application

Here is an idea, we will add three images (ImageControls) to our application and on theirs LeftMouseButtonDown Event we will display the PopUp. So I have taken the help of Blend 3 to design the application. It will have 3 Images as Home, Search and Reports. The following figure displays our application.

Figure 1.2 Designing our Application
Adding a PopUp Control

This is actually disturbing; you can't find the control in the toolbox. But if you start typing the control name it will satisfy you. So I have added some controls like Border, StackPanel and Displaying Text and Button to close the PupUp.
    <Popup x:Name="myPopup" Margin="-34,0,-31,0" Grid.Row="2" Grid.Column="1" Height="78" VerticalAlignment="Bottom"  >    <Border CornerRadius="10" Background="Silver" BorderThickness="2" BorderBrush="Black"> 
        <StackPanel Margin="10"> 
                    <TextBlock x:Name="PopUpText"/> 
                    <Button x:Name="PopUpButton" Height="30" Width="90" Content="Close" Click="PopUpButton_Click" /> 
        </StackPanel> 
        </Border> 
    </Popup> 


PopUp Control has a unique property called IsOpen which returns a boolean value of either true or false. The default value is always false. With this concept in mind let's add some events and use this property to control the show of the PopUp.

Calling the PopUp Control
As we discussed earlier we can handle the display of the PopUp by using the property IsOpen. Now we will see how we have used in our sample application.
    private void PopUpButton_Click(object sender, RoutedEventArgs e) 
    { 
          myPopup.IsOpen = false; 
    } 
     
    private void Home_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
          PopUpText.Text = "You Clicked Home"; 
          myPopup.IsOpen = true; 
    } 
     
    private void Search_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
          PopUpText.Text = "You Clicked Search"; 
          myPopup.IsOpen = true; 
    } 
     
    private void Reports_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
          PopUpText.Text = "You Clicked Reports"; 
          myPopup.IsOpen = true; 
    } 

Running the Application
When you click different images you will be notified by the PopUp Control.

image3.gif

Figure 1.3 PopUp is displayed

That's it, we have successfully used the PopUp Control. Enjoy Coding.

 

 

 



European Silverlight Hosting - Amsterdam :: Working with the Slider Control in Silverlight 5

clock November 1, 2019 09:49 by author Peter

The Slider control in Silverlight 5 is used to allow a user to select from a range of values by sliding it along a track. You can create a horizontal or vertical slider. You can specify the range of values and the precision of movement too. The Slider class that represents this control is defined in the System.Windows.Controls namespace. Some of the commonly used properties of this class are:

To demonstrate the use of the Slider control, let us create a TextBox with some text which is enlarged or shrunk depending upon the slider value. Create a Silverlight 5 application and replace the Grid tag with the Canvas tag. Drag and drop the Slider from the Toolbox into your XAML code (between the Canvas tags). Also drag and drop an TextBox control. The sole reason for using a TextBox here instead of TextBlock is that a TextBlock does not support the Background property and we wish to specify a background here for the control containing the text.

Configure the properties of the controls as shown below:

<UserControl x:Class="Imager.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"
      mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
     <Canvas x:Name="LayoutRoot" Width="640" Height="480">
         <TextBox Name="txtMsg" Canvas.Left="40" Canvas.Top="30" Height="22" Width="132" Text="Silverlight Rocks!" Background="Aqua" IsReadOnly="True"  />
         <Slider Name="slider"  Background="Transparent" Height="25" Width="150" Maximum="150" Minimum="0" SmallChange="5" ValueChanged="Slider_ValueChanged" IsDirectionReversed="False" ></Slider>

     </Canvas>
</UserControl>

The code accomplishes the following:

  • Creates a canvas of height 480 and width 640
  • Creates a TextBox with the text "Silverlight Rocks!" and positions it on the canvas at 40,30 location.
  • Creates a Slider control with transparent background, maximum 150 and minimum 0, small change (precision of movement) as 5 and height and width as 25 and 150 respectively.
  • Creates an event handler for Value Changed event of Slider.

Now open the MainPage.xaml.cs and add the following code:
public partial class MainPage : UserControl

    {
        double start, end, height, width, size;
        public MainPage()
        {
             InitializeComponent();
             //original values of the slider

            start = slider.Minimum;
            end = slider.Maximum;

            //original height and width of the text box

            height = txtMsg.Height;
            width = txtMsg.Width;
            size = txtMsg.FontSize; 
        }
        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // If slider has reached the beginning

            if (e.NewValue == start)
            {
                txtMsg.Height = height;
                txtMsg.Width = width;
                txtMsg.FontSize = size;
            }

            //if slider has moved forward

            if (e.NewValue > e.OldValue)
            {
                txtMsg.Height = height + e.NewValue;
                txtMsg.Width = width + e.NewValue;
                txtMsg.FontSize += 1;
            }
            else //if slider has moved backward
            {
                txtMsg.Height = txtMsg.Height - (e.OldValue-e.NewValue);
                txtMsg.Width = txtMsg.Width - (e.OldValue - e.NewValue);
                txtMsg.FontSize -= 1;
            }
        }
    }

The logic in this code is self explanatory from the comments. When you build and execute your solution and move the slider, you will see the text increasing or decreasing in size. Though this was a simple demonstration, in actual scenarios, you can customize the Slider control through its various properties. You can also enhance its design characteristics in Expression Blend 4 if required.



European Silverlight Hosting - Amsterdam :: How To Control Playback of Media Using a MediaElement of Silverlight?

clock October 18, 2019 11:42 by author Peter

We can integrate media into our Silverlight pages and WPF UserControls. The MediaElement object provides several media-specific properties. The following list describes the commonly used properties.

  •     AutoPlay: Specifies whether the MediaElement should begin playing automatically. The default value is True.
  •     IsMuted: Specifies whether the MediaElement is silenced. A value of True mutes the MediaElement. The default value is False.
  •     Stretch: Specifies how video is stretched to fill the MediaElement object. Possible values are None, Uniform, UniformToFill, and Fill. The default is Fill.
  •     Volume: Specifies the volume of the MediaElement object’s audio as a value from 0 to 1, with 1 being the loudest. The default value is 0.5.

In addition to its media-specific properties, MediaElement also has all the properties of a UIElement, such as Opacity and Clip.

Controlling Media Playback
You can control media playback by using the Play, Pause, and Stop methods of a MediaElement object.
<Canvas
    xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="CanvasLoaded">
    <MediaElement x:Name="MyMedia" Stretch="Uniform"
        Source="/images/Silverlight_Small.wmv" Height="200" Width="200" />
  <Canvas x:Name="ButtonPanel">
      <Canvas Background="Red" Canvas.Left="10" Canvas.Top="185" Height="25" Width="50"
        MouseLeftButtonDown="StopMedia" Cursor="Hand">
        <Rectangle Height="30" Width="40" Canvas.Left="10" />
        <TextBlock Text="Stop" Canvas.Left="10" Foreground="Yellow" />
       </Canvas>
       
       <Canvas Background="Green" Canvas.Left="70" Canvas.Top="185" Height="25" Width="50"
        MouseLeftButtonDown="PlayMedia" Cursor="Hand">
        <Rectangle Height="30" Width="40" Canvas.Left="10" />
        <TextBlock Text="Play" Canvas.Left="10" Foreground="Yellow" />
       </Canvas>
       
       <Canvas Background="Blue" Canvas.Left="130" Canvas.Top="185" Height="25" Width="60"
        MouseLeftButtonDown="PauseMedia" Cursor="Hand">
        <Rectangle Height="30" Width="40" Canvas.Left="10" />
        <TextBlock Text="Pause" Canvas.Left="10" Foreground="Yellow" />
       </Canvas>
       
       <Canvas Background="Black" Canvas.Left="10" Canvas.Top="215" Height="25" Width="180"
        MouseLeftButtonDown="ToggleFullScreen" Cursor="Hand">
        <Rectangle Height="30" Width="40" Canvas.Left="10" />
        <TextBlock Text="Full Screen" Canvas.Left="55" Foreground="Yellow" />
       </Canvas>
    </Canvas>
  </Canvas>    

// --------- JavaScript Code to control the Media object -------------
// Fires when Canvas is loaded
function CanvasLoaded(sender, args)
{
    var canvas = sender.getHost();
    canvas.content.onfullScreenChange = onFullScreenChanged;                            
}
// Fires when Full screen is changed
function onFullScreenChanged(sender, args)
{
    var canvas = sender.getHost();
    var buttonPanel = sender.findName("ButtonPanel");
    // Change the opacity of the button panel so that in the full screen it disappears and in normal screen it appears
    if (canvas.content.fullScreen == true)
        buttonPanel.opacity = 0;
    else
        buttonPanel.opacity = 1;
    // change the media object height and width to the canvas height and width
    var media = sender.findName("MyMedia");
    media.width = canvas.content.actualWidth;
    media.height = canvas.content.actualHeight;
}
//Fires when Full Screen button is clicked
function ToggleFullScreen(sender, args)
{
    var canvas = sender.getHost();
    canvas.content.fullScreen = !canvas.content.fullScreen;
}
// Fires when Stop button is clicked
function StopMedia(sender, args)
{
    sender.findName("MyMedia").stop();
}
// Fires when Play button is clicked
function PlayMedia(sender, args)
{
    sender.findName("MyMedia").play();
}
// Fires when Pause button is clicked
function PauseMedia(sender, args)
{
    sender.findName("MyMedia").pause();

Hope this helps!!



Silverlight Hosting - HostForLIFE.eu :: Overcome Silverlight Caching when using CRM OData Endpoint

clock August 30, 2019 12:31 by author Peter

The Problem

Recently I was creating a Silverlight based app for one of our customers on my Silverlight 5 Hosting. The applications runs on the contact form embedded in an IFrame. It used OData to retrieve a defined set of columns for the contact. All was looking nice, until I noticed, that after changing some of the columns and saving the contact, my Silverlight application still used old data – even after refreshing the page.

Internally it used an HttpWebRequest object to retrieve data from CRM via a URL like /XrmServices/2011/OrganizationData.svc/ContactSet(GUID’{0}’)?$select=FullName. Unfortunately Silverlight aggressively caches Web-Requests. Since the URL for a contact never changes, Silverlight does not even really do a further request and pulls data from the cache instead. The HttpWebRequest class in the Silverlight Framework does not provide means to disable caching. There are a lot of posts and forum topics out there discussing that problem.

The solution
Obviously the problem is, that the URL does not change. To overcome the caching issue, we just have to make sure, the address changes on every request. The solution I came up with was simply adding a made up parameter to the URL. Fortunately the OData Endpoint simply ignores unknown parameters. I called it ignoreCache, but of course any name will do here. The value of that parameter will be set to basically the current time. Now the URL changes on every request and we can work with the actual data:

Dim urlRaw As String = String.Format(“/XrmServices/2011/OrganizationData.svc/ContactSet(GUID’{0}’)?$select=FullName&IgnoreCache={1}”, id, Date.Now.TimeOfDay.Ticks)



Silverlight 5 Hosting UK - HostForLIFE.eu :: How to fixed Silverlight Control Content always null from Javascript Access

clock August 16, 2019 09:39 by author Peter

Today, I am going to show you how to fixed Silverlight 5 Control Content always null from Javascript Access. I got an Error when  I try to access the Silverlight object from the client side. Here’s the following snippet code from client site.

function search() {
            try {
                var silverLightControl = document.getElementById("silverlightControl");
                silverLightControl.Content.Page.SetUser(document.getElementById("txtUser").value);
            } catch (e) {
                alert(e.description);
            }
        }

The page with silverlight object embedded
    <div id="silverlightControl">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/SLAspxCommunication.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="5.0.61118.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>


At the silverlight object class,  we have registered the page as javascriptable object with following line

HtmlPage.RegisterScriptableObject("Page", this);

public MainPage()
        {
            InitializeComponent();
            _users = GenerateList();
            HtmlPage.RegisterScriptableObject("Page", this);
        }


The function looks simple that I just want to call the Silverlight function to search the user, unfortunately. This error message below always popped up.

When I debug the process, it indicate that the control did not contain a Content element.  This Error
var silverLightControl = document.getElementById("silverlightControl");

It will load the Div Control instead of the object container that host the silverlight object.  After I set the id to be silverlightControl for the object tag. then  search function funtion well and access the SetUser function in the silverlight object.
   <div>
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%" id="silverlightControl">
          <param name="source" value="ClientBin/SLAspxCommunication.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="5.0.61118.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>



Silverlight 6 Hosting - HostForLIFE.eu :: Code to download pdf file in silverlight

clock July 26, 2019 11:08 by author Peter

Hi, I want to download a pdf file form silverlight application , the pdf file is in a folder in my solution , i want to give the path of the pdf to the method and it should download the pdf to the local system. i am happy to say that i achieved it with the following code:
SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "pdf Files|*.pdf";
                dialog.DefaultFileName = "BeneficiaryDesignation.pdf";
                if (dialog.ShowDialog() ?? false)
                {


                    WebClient webClient = new WebClient();
                    webClient.OpenReadCompleted += (s, e2) =>
                    {
                        try
                        {
                            using (Stream fs = (Stream)dialog.OpenFile())
                            {
                                e2.Result.CopyTo(fs);
                                fs.Flush();
                                fs.Close();
                            }
                           
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    };
                    string str = App.Current.Host.Source.AbsoluteUri;
                    string path = App.appConfiguration.GetPDFPath("BeneficiaryDesignation.pdf");
                    str = str.Replace("/ClientBin/ProjectDemo.xap", path);                    
                   
                    webClient.OpenReadAsync(new Uri(str), UriKind.RelativeOrAbsolute);
                }

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 5 Hosting France - HostForLIFE.eu :: Create an Exception Logger in Silverlight

clock June 21, 2019 11:42 by author Peter

In this post I'll describe the way to handle the exceptions in Silverlight. Whereas running the Silverlight application, if any exception happens it'll attend Silverlight.js and show within the internet explorer as a javascript error. Within the debugging purpose of read typically it's cumbersome to see wherever truly the exception happened.

LogWindow.xaml
This is an easy user control that has an easy textbox:
<TextBox
AcceptsReturn="True"
TextAlignment="Left"
TextWrapping="NoWrap"
VerticalScrollBarVisibility="Visible"
x:Name="logText"
FontFamily="Courier New"
FontSize="12" IsReadOnly="True" HorizontalScrollBarVisibility="Auto" />

Logger.cs
This class are used to print the exception and notice the stacktrace. it's an enum for the exception types viz. DEBUG,INFO,WARN,ERROR and FATAL.This class contains an easy delegate to add text to the log window.
The static property _instance is about by the LogWindow.xaml.cs go in the load event as:
Logger._instance = logText;
So that it will print whatever exception happenes in your application. The LogException methodology expects exception object because the parameter and find the exception information using the StackFrame class.

StackFrame frame = new StackFrame(true);
callerSignature =  string.Format("@{0}:{1}:{2}", frame.GetMethod(), frame.GetFileName(), frame.GetFileLineNumber());


To use this method in your catch block you just simply need to call the static method as:
Catch(Exception ex)
{
Logger.LogException(ex);
}

Hope this tutorial works for you!



Silverlight 6 Hosting - HostForLIFE.eu :: Print Document In Silverlight

clock May 23, 2019 05:30 by author Peter

How we can print the document in a Silverlight application.

Step 1
We have the PrintDocument Class which defines a reusable object that sends output to a printer.
    PrintDocument
    The PrintDocument object encapsulates all the information needed to print a page. They associate with the control which content can be print. They handle the events and operations of printing.
    Namespace - System.Drawing.Printing.PrintDocument

    [C#]

    public class PrintDocument : Component

    
We can create an instance of the PrintDocument class, set the properties that describe how to print, and call the Print method to start the printing process. Handle the PrintPage event where you specify the output to print, by using the Graphics included in the PrintPageEventArgs.
    Associate control to Print document
        private void printDoc_PrintPage(object sender, PrintPageEventArgs e) { 
            // print current page 
            e.PageVisual = printPage; 
        } 


Step 2
Create one user control page name as PrintPage.Xaml and design header and footer in this user control page like as following.
    <Grid x:Name="LayoutRoot" Background="White"> 
        <Grid.RowDefinitions> 
            <RowDefinition Height="Auto" /> 
            <RowDefinition /> 
            <RowDefinition Height="Auto" /> 
        </Grid.RowDefinitions> 
        <!--Header--> 
        <Grid> 
            <TextBlock Text="HEADER" /> 
        </Grid> 
        <!--Body--> 
        <ItemsControl Name="BodyItemsControl" Grid.Row="1" Margin="0,24" /> 
        <ItemsControl Name="TemplateItemsControl"> 
            <ItemsControl.ItemTemplate> 
                <DataTemplate> 
                    <Grid> 
                        <Grid.ColumnDefinitions> 
                            <ColumnDefinition Width="Auto" /> 
                            <ColumnDefinition Width="Auto" /> 
                            <ColumnDefinition Width="*" /> 
                        </Grid.ColumnDefinitions> 
                        <TextBlock Text="{Binding ID}" Margin="2" /> 
                        <TextBlock Text=" - " Grid.Column="1" Margin="2" /> 
                        <TextBlock Text="{Binding Description}" Grid.Column="2" TextWrapping="Wrap" MaxWidth="500" HorizontalAlignment="Left" Margin="2" /> 
                    </Grid> 
                </DataTemplate> 
            </ItemsControl.ItemTemplate> 
        </ItemsControl> 
        <Grid Grid.Row="2"> 
            <TextBlock Text="FOOTER" /> 
        </Grid> 

Step 3
In MainPage.Xaml create an instance of PrintDocument like as following.
    public MainPage() { 
        InitializeComponent(); 
        this.Loaded += new RoutedEventHandler(MainPage_Loaded); 
    } 
    void MainPage_Loaded(object sender, RoutedEventArgs e) { 
        GetItems(); 
        printDoc.PrintPage += newEventHandler < PrintPageEventArgs > (printDoc_PrintPage); 
    } 
    //following items for printing. 
    privatevoid GetItems() { 
        for (int i = 0; i < 100; i++) { 
            items.Add(newItem() { 
                ID = i, 
                    Description = "This is Print Document " + i 
            }); 
        } 
    } 
    //Handling the event when we're printing: 
    private void printDoc_PrintPage(object sender, PrintPageEventArgs e) { 
        PrintPage printPage = new PrintPage(); 
        // print current page 
        e.PageVisual = printPage; 
        e.HasMorePages = true; 
        break; 
    } 
 

Step 4
Add a button to the MainPage.Xaml and print the document when the button is clicked,
    <Button Content="Button" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="42,56,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
        printDoc.Print("Printing A Page"); 
    } 


Step 5

Output look like as following,

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight Hosting France - HostForLIFE.eu :: Use ScrollViewer Layout Panel in Silverlight

clock May 17, 2019 11:36 by author Peter

In this post allow us to understand how to use ScrollViewer panel Layout inside a Silverlight application. ScrollViewer is an additional layout container, that we don’t use constantly. It's chiefly useful showing contents in an exceedingly scrollable panel such as ListBox or Editor window. ListBox, TextBox, RichTextBox internally uses ScrollViewer to implement the scrolling functionality. Allow us to discuss the implementation in this post.

As usual, open up visual studio and choose Silverlight project. We will discover there's a Grid layout in your MainPage. xaml. Eliminate the default Grid layout and merely drag and drop the Stack panel Layout into our application. The code for this looks such as:
<StackPanel x:Name="LayoutRoot" > </StackPanel>

Inside the stack panel I am just defining 12 different rectangles.  And this is the code that I used:
<StackPanel x:Name="LayoutRoot" Orientation="Vertical" Width="100">
            <Rectangle Height="50" Width="100" Fill="Red" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Orange" />
            <Rectangle Height="50" Width="100" Fill="Tomato" />
            <Rectangle Height="50" Width="100" Fill="WhiteSmoke" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Yellow" />
            <Rectangle Height="50" Width="100" Fill="Azure" />
            <Rectangle Height="50" Width="100" Fill="Gold" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Violet" />
        </StackPanel>


In case we compile the above code as it's, we will notice all of the rectangles however no scroll bar result. Thus in an effort to get scroll bar effect we ought to put the above stack panel inside scroll viewer and ought to offer fixid width towards the scroll viewer. And this is the code snippet:
<ScrollViewer Height="200" >
        <StackPanel x:Name="LayoutRoot" Orientation="Vertical" Width="100">
            <Rectangle Height="50" Width="100" Fill="Red" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Orange" />
            <Rectangle Height="50" Width="100" Fill="Tomato" />
            <Rectangle Height="50" Width="100" Fill="WhiteSmoke" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Yellow" />
            <Rectangle Height="50" Width="100" Fill="Azure" />
            <Rectangle Height="50" Width="100" Fill="Gold" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Violet" />
        </StackPanel>
    </ScrollViewer>

Finally, Run the code and here is the result:



European Silverlight 6 Hosting HostForLIFE.eu :: How to access controls in DataGrid TemplateColumn header?

clock April 25, 2019 11:20 by author Peter

A data grid view is a rectangular control made of columns and rows. I have a DataGrid where I have included some controls in column header. Each column is a Template column. These controls appear just below the column header which are used for entering filter information. Here's the issue on my code on Silverlight 5.


VisualTreeHelper class helps to iterate through the visual tree of the xaml. Using it we can find the child and parent controls of the rendered controls. Lets check the Visual Tree of the rendered control using Silverlight Spy.

The Following Method do a search over the child controls with in a control recursively and returns the control based on Name.

private object GetChildControl(DependencyObject parent, string controlName)

    Object tempObj = null;
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int counter = 0; counter < count; counter++)
    {
        //Get The Child Control based on Index
        tempObj = VisualTreeHelper.GetChild(parent, counter);
        //If Control's name Property matches with the argument control
        //name supplied then Return Control
        if ((tempObj as DependencyObject).GetValue(NameProperty).ToString() == controlName)
            return tempObj;
        else //Else Search Recursively
        {
            tempObj = GetChildControl(tempObj as DependencyObject, controlName);
            if (tempObj != null)
                return tempObj;
        }
    }
    return null;
}

Make sure that the same has to be delegated to UI thread using Dispatcher. As the controls created using UI Thread can not be accessed from other thread.
//Access the Grid Header Controls
Dispatcher.BeginInvoke(delegate
{
    var hyperlinkControl = GetChildControl(dataGrid1, "hlSort");
    var checkControl = GetChildControl(dataGrid1, "chkSelectAll");
});



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in