top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Use Resource Management In Silverligt 3?

+6 votes
409 views

The files required for any Application to run other than project related files are called resources. It can be a text file or image file or any other file. In this article, we will be seeing how images can be accessed in various ways in a Silverlight application.

Types of Resource Management

There are 3 ways we can manage resources such as:

  1. Add Image as Resource

  2. Add Image as Content

  3. Add Image as Resource in an external assembly

Create a Silverlight Project

image1.gif

Figure 1.1 Creating Silverlight Project

Designing the Application

For our sample application let's put 3 Image Control, 3 Buttons and 3 TextBlocks to display the type of resource. I have used blend to design the application.

image2.gif

Figure 1.2 Designing the Application

Add Images to the Project

In SampleSilverlightApplication project add a folder called images and two images are added. As you can see the images we are going to change the Build Action of the images. We will change the Build Action for firefox.png to Resource and IE.png to Content.

image3.gif

Figure 1.3 Adding images to the project

image4.gif

Figure 1.4 Changing the Build Action of the Images.

Adding another Project

To use Image from another assembly we need to add project to the solution and we will add the Image to it. Then we will add the project refference to our main project (SampleSilverlightApplication).

image5.gif

Figure 1.5 Adding another project to the Solution and adding Images to the added project

We have just added One Silverlight Class Library to the Solution and added the folder images and ofcourse we added chrome.png. The SecondApplicaion reference is added to the SampleSilverlightApplication.

Accessing all the Image Resources

Remember we have added 3 Buttons to our SampleSilverlightApplication; now it's time to use them.
First of all we will access the Image which is made Resource in Build Action

private void btnResource_Click(object sender, RoutedEventArgs e)
        {
            /*Image Resource*/
            Uri uri = new Uri("/SampleSilverlightApplication;component/images/firefox.png", UriKind.Relative);
            StreamResourceInfo streamResource = Application.GetResourceStream(uri);

            BitmapImage image = new BitmapImage();
            image.SetSource(streamResource.Stream);
            MyImageResource.Source = image;
        }

Then we will access the Image which is made Content in Build Action

private void btnContent_Click(object sender, RoutedEventArgs e)
        {
            /*Content Resource*/
            Uri uri = new Uri("images/IE.png", UriKind.Relative);
            StreamResourceInfo streamResource = Application.GetResourceStream(uri);

            BitmapImage image = new BitmapImage();
            image.SetSource(streamResource.Stream);
            MyImageContent.Source = image;|
        }

And last but not the least we will try to access the Image from another project (assembly).

private void btnAssembly_Click(object sender, RoutedEventArgs e)
        {
            /*Add Image as Resource in an external assembly*/
            Uri uri = new Uri("/SecondApplication;component/images/chrome.png", UriKind.Relative);
            StreamResourceInfo streamResource = Application.GetResourceStream(uri);

            BitmapImage image = new BitmapImage();
            image.SetSource(streamResource.Stream);
            MyImageAssembly.Source = image;
        }

Running the Application

image6.gif

Figure 1.6 Accessing all the resources on button click event

Congratulations you have successfully used all the resources, and our Application will look like the following. Enjoy coding.

posted Dec 28, 2015 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

In this article we will explore on Pie Chart in Silverlight 3. Pie Chart comes with Silverlight 3 Toolkit.

Crating Silverlight Project

Fire up Expression Blend 3 and create a Silverlight Application. Name it as PieChartInSL3.

PieChartImg1.gif

 

Go ahead and add a Pie Series into your application.

You can find it in Asset Library.

PieChartImg2.gif

By adding a Pie Series, you just added an Assembly System.Windows.Controls.DataVisualization.

And Blend automatically refers to the Namespace.

If you see the xaml code behind you will find the following:

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

Now we will add some data into it.

Create a class called Appointment and add the following code into it.

public class Appointment

    {

        public int Id { get; set; }

        public string AppName { get; set; }

        public string AppointmentDetails { get; set; }

        public int Duration { get; set; }

 

        public Appointment()

        {

        }

 

        public Appointment(int id, string appName, string appointmentDetails, int duration)

        {

            Id = id;

            AppName = appName;

            AppointmentDetails = appointmentDetails;

            Duration = duration;

        }

 

    }

Pie Series takes Key Value pair as it's data. So we will create a class named AppointmentHelper which will convert a Dictionary to Key Value Pair.

 

public static Dictionary<String, int> GetTimeDistribution(this List<Appointment> appts)

        {

            Dictionary<String, int> myTimeDistribution = new Dictionary<string, int>();

 

            var appointments = (from time in appts

                                select time.AppName).Distinct();

 

            foreach (var app in appointments)

            {

                var time = (from pjts in appts

                            where pjts.AppName == app

                            select pjts.Duration).Sum();

 

                myTimeDistribution.Add(app, time);

 

            }

            return myTimeDistribution;

        }

 

Now we will add values.

List<Appointment> appointments;

 

                                public MainPage()

                                {

                                                InitializeComponent();

                CreateTimeLists();

                                }

 

        private List<AppointmentDTO> CreateTimeLists()

        {

            appointments = new List<Appointment>

            {

                new Appointment { Id=1, AppName="Meeting", AppointmentDetails="Video COnference", Duration=30},

                new Appointment { Id=1, AppName="Call", AppointmentDetails="Audio COnference", Duration=90},

                new Appointment { Id=1, AppName="Session", AppointmentDetails="Session for Silverlight", Duration=120}

            };

            return appointments;

        }

Now we will bind our data to Pie Series.

<chartingToolkit:Chart x:Name="TypicalChart" Title="Typical Pie Chart">

            <chartingToolkit:Chart.Series>

                <chartingToolkit:PieSeries Margin="0,0,20,20" d:LayoutOverrides="Width, Height" Title="Pie Chart Sample"IndependentValueBinding="{Binding Path=Key}"

                    DependentValueBinding="{Binding Path=Value}"/>

            </chartingToolkit:Chart.Series>

        </chartingToolkit:Chart>

As you see from the above code I have added two properties as IndependentValueBinding and DependentValueBinding. We need to give the Binding Path to respective key and value.

Now Type cast the chart to Pie Series and assign the ItemSource property.

private void UserControl_Loaded(object sender, RoutedEventArgs e)

        {

            ((PieSeries)TypicalChart.Series[0]).ItemsSource = appointments.GetTimeDistribution();

        }

 

Now go ahead run the application to see the Pie Chart.

PieChartImg3.gif

That's it you have successfully used Pie Series in Silverlight 3.

READ MORE

Microsoft has released Silverlight 3 recently. Good news is Microsoft has released a Release Candidate for Expression Blend 3 also. It's called Expression Blend 3 + Sketch Flow. There are several enhancements from the old Expression Blend 3 Mix 09 Preview. In this article we will be discussing some of the Templates those are added into this release.

Starting with a New Project in Expression Blend 3

In Expression Blend 3 RC release a new concept is added called Sketch Flow. So some templates are with Sketch Flow and some are as usual template. I will be giving brief introduction about all templates. Following are the templates can be found in Expression Blend 3 RC.

image1.gif

Figure 1.1 Normal Silverlight 3 Templates by default.

image2.gif

Figure 1.2 After expanding the Left Pane we can see Two Project types.

image3.gif

Figure 1.3 Expanding the Project Types you will find Sketch Flow project inside it.

image4.gif

Figure 1.4 Displaying the templates available for a WPF Project type. 

These are the common templates found in Expression Blend 3 RC. 
 

READ MORE

Calendar Events

Besides the normal control events, the Calendar control has three events calendar related events. These events are the DisplayDateChanged, DisplayModeChanged and SelectedDatesChanged. The DisplayDateChanged event is fired where the DisplayDate property is changed. The DisplayModeChanged event is fired when the DisplayMode property is changed. The SelectedDatesChanged event is fired when the SelectedDate or SelectedDates properties are changed. The following code snippet sets these three events attributes. 

<Calendar SelectionMode="SingleRange"  
   Name="MonthlyCalendar"   
   SelectedDatesChanged="MonthlyCalendar_SelectedDatesChanged"  
   DisplayDateChanged="MonthlyCalendar_DisplayDateChanged"  
   DisplayModeChanged="MonthlyCalendar_DisplayModeChanged"  
   HorizontalAlignment="Left"  
   VerticalAlignment="Top"  
   Margin="10,10,0,0">   
</Calendar>   

The code behind for these events look as in Listing 4. 

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
{  
}  
private void MonthlyCalendar_DisplayDateChanged(object sender,   
    CalendarDateChangedEventArgs e)  
{  
}  
private void MonthlyCalendar_DisplayModeChanged(object sender,   
    CalendarModeChangedEventArgs e)  
{  
 

Listing 4

Normally, on a date selection, you may want to capture that event and know what the current selected date is. Now how about we add a TextBox control to the page and on the date selection, we will set the text of the TextBox to the currently selected date. 

We add the following code to the XAML just below the Calendar control. <TextBox Width="200" Height="30"  
   VerticalAlignment="Bottom"  
   HorizontalAlignment="Left"  
   Margin="10,10,10,10"  
   x:Name="SelectedDateTextBox">  
</TextBox>

On the SelectedDateChanged event handler, we set the TextBox.Text property to the SelectedDate property of the Calendar control as you can see from the code in Listing 5. 

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
{  
    SelectedDateTextBox.Text = MonthlyCalendar.SelectedDate.ToString();  

Listing 5

Now when you run the application, you will see the output that looks as in Figure 10. When you select a date in the Calendar, it will be displayed in the TextBox. 


Figure 10

Formatting a Calendar


How about we create a Calendar control with a border formatting, background and foreground of the Calendar?

The BorderBrush property of the Calendar sets a brush to draw the border of a Calendar. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of the colors Red and Blue.

<Calendar.BorderBrush>  
   <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
      <GradientStop Color="Blue" Offset="0" />  
      <GradientStop Color="Red" Offset="1.0" />  
   </LinearGradientBrush>  
</Calendar.BorderBrush>  

The Background and Foreground properties of the Calendar set the background and foreground colors of a Calendar. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Calendar. 

<Calendar.Background>  
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
        <GradientStop Color="Blue" Offset="0.1" />  
        <GradientStop Color="Orange" Offset="0.25" />  
        <GradientStop Color="Green" Offset="0.75" />  
        <GradientStop Color="Red" Offset="1.0" />  
    </LinearGradientBrush>  
</Calendar.Background>  
<Calendar.Foreground>  
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
        <GradientStop Color="Black" Offset="0.25" />  
        <GradientStop Color="Green" Offset="1.0" />  
    </LinearGradientBrush>  
</Calendar.Foreground>  

The new Calendar looks as in Figure 11. 


Figure 11

Setting Image as Background of a Calendar


To set an image as the background of a Calendar, we can set an image as the Background of the Calendar. The following code snippet sets the background of a Calendar to an image. The code also sets the opacity of the image.

<Calendar.Background>  
   <ImageBrush ImageSource="Garden.jpg" Opacity="0.3"/>  
</Calendar.Background>  

The new output looks as in Figure 12.


Figure 12

Creating a Calendar Dynamically


The code listed in Listing 6 creates a Calendar control programmatically. First, it creates a Calendar object and sets its DisplayMode and SelectedMode and other properties and later the Calendar is added to the LayoutRoot. 

private void CreateDynamicCalendar()  
{  
    Calendar MonthlyCalendar = new Calendar();  
    MonthlyCalendar.Name = "MonthlyCalendar";  
    MonthlyCalendar.Width = 300;  
    MonthlyCalendar.Height = 400;  
    MonthlyCalendar.Background = Brushes.LightBlue;  
    MonthlyCalendar.DisplayMode = CalendarMode.Month;  
    MonthlyCalendar.SelectionMode = CalendarSelectionMode.SingleRange;  
    MonthlyCalendar.DisplayDateStart = new DateTime(2010, 3, 1);  
    MonthlyCalendar.DisplayDateEnd = new DateTime(2010, 3, 31);  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 5));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 15));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 25));    
    MonthlyCalendar.FirstDayOfWeek = DayOfWeek.Monday;  
    MonthlyCalendar.IsTodayHighlighted = true;    
    LayoutRoot.Children.Add(MonthlyCalendar);  
}  

Listing 6

Summary


In this article, I discussed the calendar control using XAML and C#. We also saw how to set display modes, selection modes, blackout dates, selected dates, border, background and foreground properties. After that, we saw you to set an image as the background of a Calendar. In the end of this article, we saw how to create a Calendar dynamically.

READ MORE

   PART 2: Continuous 

 <ListBoxItem Background="LightCoral" Foreground="Red"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">                  
        <CheckBox Name="CoffieCheckBox">  
            <StackPanel Orientation="Horizontal">  
            <Image Source="coffie.jpg" Height="30"></Image>  
            <TextBlock Text="Coffie"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightGray" Foreground="Black"   
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="TeaCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="tea.jpg" Height="30"></Image>  
            <TextBlock Text="Tea"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightBlue" Foreground="Purple"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
    <CheckBox Name="OrangeJuiceCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="OrangeJuice.jpg" Height="40"></Image>  
            <TextBlock Text="OrangeJuice"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightGreen" Foreground="Green"   
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="MilkCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="Milk.jpg" Height="30"></Image>  
            <TextBlock Text="Milk"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightBlue" Foreground="Blue"   
             FontFamily="Verdana" FontSize="12" FontWeight="Bold">  
    <CheckBox Name="IcedTeaCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="IcedTea.jpg" Height="30"></Image>  
            <TextBlock Text="Iced Tea"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  
<ListBoxItem Background="LightSlateGray" Foreground="Orange"  
             FontFamily="Georgia" FontSize="14" FontWeight="Bold">  
    <CheckBox Name="MangoShakeCheckBox">  
        <StackPanel Orientation="Horizontal">  
            <Image Source="MangoShake.jpg" Height="30"></Image>  
            <TextBlock Text="Mango Shake"></TextBlock>  
        </StackPanel>  
    </CheckBox>  
</ListBoxItem>  

Now, the new ListBox looks as in Figure 6.

ListBox with CheckBoxes
                                 Figure 6. ListBox with CheckBoxes

Data Binding 

Before I discuss data binding in general, I must confess, Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have some bigger plans for the future but so far I have seen binding using dependency objects and properties, LINQ and DLINQ and WCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they clean up this mess in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of ways a data can be consumed from:

  • Objects
  • A relational database such as SQL Server
  • A XML file
  • Other controls

Data Binding with Objects

The ItemsSource property of a ListBox binds a collection of IEnuemerable items such as an ArrayList to the ListBox control. 

// Bind ArrayList with the ListBox  
LeftListBox.ItemsSource = LoadListBoxData();  

private ArrayList LoadListBoxData()  
{  
    ArrayList itemsList = new ArrayList();  
    itemsList.Add("Coffie");  
    itemsList.Add("Tea");  
    itemsList.Add("Orange Juice");  
    itemsList.Add("Milk");  
    itemsList.Add("Mango Shake");  
    itemsList.Add("Iced Tea");  
    itemsList.Add("Soda");  
    itemsList.Add("Water");  
    return itemsList;  
}  

Sample: Transferring data from one ListBox to Another 


We've seen many requirements where a page has two ListBox controls and the left ListBox displays a list of items and using a button we can add items from the left ListBox and add them to the right side ListBoxand using the remove button we can remove items from the right side ListBox and add them back to the left side ListBox

This sample shows how to move items from one ListBox to another. The final page looks as in Figure 7. The Add button adds the selected item to the right side ListBox and removes from the left side ListBox. The Remove button removes the selected item from the right side ListBox and adds back to the left sideListBox.

ListBox
                                                                           Figure 7

add remove
                                                                           Figure 8

 

PART 4: will update soon

READ MORE

Part 2 Continous:


                   <TreeViewItem Name="Child1">  

                       <TreeViewItem.Header>  

  1.             <CheckBox Name="CoffieCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="coffie.jpg" Height="30"></Image>  
                        <TextBlock Text="Coffie"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>   
        </TreeViewItem>  
        <TreeViewItem Name="Child2">  
            <TreeViewItem.Header>  
                <CheckBox Name="IcedTeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="IcedTea.jpg" Height="30"></Image>  
                        <TextBlock Text="Iced Tea"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child3">  
            <TreeViewItem.Header>  
                <CheckBox Name="MangoShakeCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="MangoShake.jpg" Height="30"></Image>  
                    <TextBlock Text="Mango Shake"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child4">  
            <TreeViewItem.Header>  
                <CheckBox Name="MilkCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Milk.jpg" Height="30"></Image>  
                    <TextBlock Text="Milk"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child5">  
            <TreeViewItem.Header>  
                <CheckBox Name="TeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Tea.jpg" Height="30"></Image>  
                    <TextBlock Text="Tea"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child6">  
            <TreeViewItem.Header>  
                <CheckBox Name="OrangeJuiceCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="OrangeJuice.jpg" Height="30"></Image>  
                    <TextBlock Text="Orange Juice"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>                  
    </TreeViewItem>  

The new TreeView looks as in the following:

TreeView with CheckBoxes
                                    Figure 6. TreeView with CheckBoxes

Before I discuss data binding in general, I must confess, the Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have bigger plans in the future, but so far I have seen binding using dependency objects and properties, LINQDLINQWCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they solve this problem in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of the ways data can be consumed: 

  • Objects
  • A relational database such as SQL Server
  • A XML file or
  • Other controls

The ItemsSource property of a TreeView is used to bind a collection of IEnuemerables such as anArrayList to the TreeView control. 

  1. // Bind ArrayList with the TreeView  
    LeftTreeView.ItemsSource = LoadTreeViewData();              
      
    private ArrayList LoadTreeViewData()  
    {  
        ArrayList itemsList = new ArrayList();  
        itemsList.Add("Coffie");  
        itemsList.Add("Tea");  
        itemsList.Add("Orange Juice");  
        itemsList.Add("Milk");  
        itemsList.Add("Mango Shake");  
        itemsList.Add("Iced Tea");  
        itemsList.Add("Soda");  
        itemsList.Add("Water");  
        return itemsList;  
    }  


Note:  Part 4 will update soon.  

READ MORE

XAML RepeatButton in WPF

XAML RepeatButton represents a set of repeat buttons. This article shows how to use a RepeatButton control in WPF using XAML and C#. 

Creating a RepeatButton

The RepeatButton XAML element represents a WPF RepeatButton control. 

  1. <Button/>  

The Width and Height attributes represent the width and the height of a RepeatButton. The Content property sets the text of the button. The Name attribute represents the name of the control, that is a unique identifier of a control. 

The code snippet in Listing 1 creates a Button control and sets its name, height, width and content. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
</RepeatButton>  

Listing 1

The default property of a button is Content. The code snippet in Listing 2 creates the same button as created by Listing 1.

<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
   Grow  
</RepeatButton>  

Listing 2

The output looks as in Figure 1



Figure 1

Delay and Interval

The Delay and Interval properties make a RepeatButton different from a normal button. 

RepeatButton is a button that fires Click events repeatedly when it is pressed and held. The rate and aspects of repeating are determined by the Delay and Interval properties that the control exposes.

The code snippet in Listing 3 sets the Delay and Interval properties. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30"   
   Delay="500" Interval="100" >  
   Grow  
</RepeatButton>  

Listing 3

Adding a Button Click Event Handler

The Click attribute of a RepeatButton element adds the click event handler and it keeps firing the event for the given Interval and delay values. The code in Listing 4 adds the click event handler for a Button. 

<Button x:Name="DrawCircleButton" Height="40" Width="120"   
        Canvas.Left="10" Canvas.Top="10"   
        Content="Draw Circle"  
        VerticalAlignment="Top"   
        HorizontalAlignment="Left">  
Click="DrawCircleButton_Click"  
</Button>  

Listing 4

The code for the click event handler looks as in following. 

  1. private void GrowButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3. }  

Okay, now let's write a useful application. 

We will build an application with the two buttons Grow and Shrink and a rectangle. The application looks as in Figure 2.

When you click and continue pressing the Grow button, the width of the rectangle will continue to grow and when you click on the Shrink button, the width of the rectangle will shrink continuously. 



Figure 2

The final XAML code is listed in Listing 5

<Window x:Class="RepeatButtonSample.Window1"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    Title="Window1" Height="300" Width="300">  
      
    <Grid Name="LayoutRoot">  
        <RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="GrowButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="GrowButton_Click">  
            Grow  
        </RepeatButton>  
        <RepeatButton Margin="100,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="ShrinkButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="ShrinkButton_Click">  
            Shrink  
        </RepeatButton>  
          
        <Rectangle Name="Rect" Height="100" Width="100" Fill="Orange"/>  
  
    </Grid>  
</Window>  

Listing 5

Listing 6
 is the click event handlers for the buttons that change the width of the rectangle.

private void GrowButton_Click(object sender, RoutedEventArgs e)  
{  
    Rect.Width += 10;  
}  
  
private void ShrinkButton_Click(object sender, RoutedEventArgs e)  
{  
   

Listing 6

READ MORE

In this article you will learn how to create and use a CustomResource in XAML.

 

  1. Open a new Visual C# windows project.
     
  2. Add a new class named say CustomResourceTest.cs in the project folder.

    CustomResourceTest.cs
     
  3. Derive this class from CustomXamlResourceLoader Class(Case sensitive) like below:

    CustomXamlResourceLoader Class
     
  4. You will get a Namespace not found error. Resolve it by using Windows.UI.Xaml.Resources Namespace.

    Windows.UI.Xaml.Resources
     
  5. Override the GetResource Member of the parent class as below. Use the intellisense to select the member.

    getresource

    getresource1
     
  6. Replace the Code inside the GetResource Method as: (this is just a simple example). We are returning a text. We plan to show this text inside a TextBlock’s Text Property.

    TextBlock
     
  7. Inside the MainPage.cs . Add the following line of code inside the MainPage Constructor to reference the CustomResouceTest.cs Class from the Page’s XAML.

    MainPage

    Correct the NameSpace not found error by resolving it.
     
  8. Now go to the MainPage.xaml Page and Add a TextBlock as follows. Notice the Text property of the TextBlock.

    MainPage.xaml
     
  9. This results in the following output when you save, build and run the project.

    run
     
  10. What is happening here?
     
    • We created a CustomResourceClass where we inherited the Class called CustomXamlResourceLoader.
    • We override the GetResourceProperty. Don’t focus on the parameters of this method for now.
    • We replaced the code inside this method by simply returning a text.
    • To access this CustomResource from XAML we have to define the CustomXamlResourceLoader. Current property to the new instance of the Class we created. We have to do this inside the Constructor of the Codebehind page where we want to use the CustomResource.
    • We then simply assigned the value of the Text property of the textblock to the CustomResource as seen on Step 8.

Example 2:

  1. Now we will try a different example where we want to display the Text of the TextBlock based on the value we pass on. Change the text of the Mainpage.xaml as:

    Mainpage.xaml 2
     
  2. The 'sayHello' string is passed as a string to the CusomResourceTest.cs class as ResourceID parameter of the overridden class. This will be more clear as you see in the next step.
     
  3. In the CustomResourceTest.cs class , change the code as follows:

    CustomResourceTest.cs2
     
  4. The thing to understand is how we pass the ResourceID from the Text Property of the TextBlock. It is passed as the resourceID parameter. So, based on the ResourceID, we return the appropriate text we want to display on the output screen.
     
  5. So now we get output as.
  6. If we change the text property as sayByeBye.

    sayByeBye
     
  7. We get the following output:
     
READ MORE
...