top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How To Create And Use A CustomResource In XAML?

+3 votes
705 views

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:
     
posted Feb 10, 2016 by Jdk

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


Related Articles

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

The following code snippet adds blackout dates to a Calendar. 

<Calendar.BlackoutDates>  
   <CalendarDateRange Start="3/1/2010" End="3/7/2010"/>  
   <CalendarDateRange Start="3/8/2010" End="3/8/2010"/>  
   <CalendarDateRange Start="3/15/2010" End="3/15/2010"/>  
   <CalendarDateRange Start="3/22/2010" End="3/22/2010"/>  
   <CalendarDateRange Start="3/29/2010" End="3/29/2010"/>  
</Calendar.BlackoutDates>  

We can do this by adding the code listed in Listing 2. As you can see from Listing 3, the BlackoutDates.Add method takes a CalendarDateRange object, that is a collection of two DateTime objects. The first date is the start date of the range and the second date is the end date of the date range. 

private void SetBlackOutDates()  
{  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
        new DateTime(2010, 3, 1),  
        new DateTime(2010, 3, 7)  
        ));  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
        new DateTime(2010, 3, 8),  
        new DateTime(2010, 3, 8)  
        ));  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 15),  
      new DateTime(2010, 3, 15)  
      ));  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 22),  
      new DateTime(2010, 3, 22)  
      ));  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 29),  
      new DateTime(2010, 3, 29)  
      ));  
}  

Listing 2

DisplayDateStart and DisplayDateEnd


The Calendar control allows you to set the start and end display dates using the DisplayDateStart and DisplayDateEnd properties. If you see Figure 5 in the previous section, you may notice the March 2010 month calendar display starts with the March 01, 2010 date. But now, what if you want to display the dates for only the month of March 2010? We can use the DisplayStartDate and DisplayEndDate properties to control the start and end dates of a month. 

DisplayDate property represents the current date to display. 

The following code snippet sets the DisplayDate, DisplayDateStart and DisplayDateEnd attributes of the Calendar element in XAML.

<Calendar Name="MonthlyCalendar"   
   SelectionMode="MultipleRange"   
   DisplayDate="3/1/2010"  
   DisplayDateStart="3/1/2010"  
   DisplayDateEnd="3/31/2010"  
/>  

The code listed in Listing 3 makes sure the start date is March 01, 2010 and end date is March 31, 2010. The current selected date is March 05. 

private void SetDisplayDates()  
{  
   MonthlyCalendar.DisplayDate = new DateTime(2010, 3, 5);  
   MonthlyCalendar.DisplayDateStart = new DateTime(2010, 3, 1);  
   MonthlyCalendar.DisplayDateEnd = new DateTime(2010, 3, 31);  
 

Listing 3

The new calendar looks as in Figure 6. 


Figure 6

FirstDayOfWeek and IsTodayHighlighted

By default, Sunday is the first day of the week. If you would like to change it, you use the FirstDayOfWeek property. The IsTodayHightlighted property is used to highlight today. 

The following code snippet sets the FirstDayOfWeek to Tuesday and makes today highlighted.

<Calendar Name="MonthlyCalendar"   
   SelectionMode="MultipleRange"   
   DisplayDate="3/5/2010"  
   DisplayDateStart="3/1/2010"  
   DisplayDateEnd="3/31/2010"  
   FirstDayOfWeek="Tuesday"  
   IsTodayHighlighted="True"   
   xmlns:sys="clr-namespace:System;assembly=mscorlib" Margin="15,39,88,19">  

The following code snippet sets the FirstDayOfWeek to Tuesday and makes today highlighted in WPF.

MonthlyCalendar.FirstDayOfWeek = DayOfWeek.Tuesday;  
MonthlyCalendar.IsTodayHighlighted = true;

The new calendar looks as in Figure 7, where you can see the start day of the week is Tuesday.


Figure 7

Selected Date and Selected Dates


The SelectedDate property represents the current selected date. If multiple date selection is true then the SelectedDates property represents all the selected dates in a Calendar. The following code snippet sets the SelectedDates in XAML at design-time. 

<Calendar Name="MonthlyCalendar"   
    SelectionMode="MultipleRange"    
    DisplayDate="3/5/2010"  
    DisplayDateStart="3/1/2010"  
    DisplayDateEnd="3/31/2010"  
    FirstDayOfWeek="Tuesday"  
    IsTodayHighlighted="True"   
    xmlns:sys="clr-namespace:System;assembly=mscorlib" Margin="15,39,88,19">    
    <Calendar.SelectedDates>  
        <sys:DateTime>3/5/2010</sys:DateTime>  
        <sys:DateTime>3/15/2010</sys:DateTime>  
        <sys:DateTime>3/25/2010</sys:DateTime>  
     </Calendar.SelectedDates>    
</Calendar>  

The selected dates in a Calendar looks as in Figure 8 where you can see March 5th, 15th and 25th have a light blue background and represents the selected dates. 


Figure 8

The following code snippet sets the SelectedDates property in WPF at run-time. 

private void AddSelectedDates()  
{  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 5));  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 15));  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 25));  
}  

Note: If you have set the selected dates to any of the blackout dates, you will see the parser in XAML will throw an error as in Figure 9. 


Figure 9

READ MORE

A calendar control is used to create a visual calendar that lets users pick a date and fire an event on the selection of the date. This article demonstrates how to create and use a calendar control using XAML and C# in WPF.

Creating a Calendar

The Calendar element represents a calendar control in XAML as in the following:

  1. <Calendar/>  

The Calendar control is defined in the System.Windows.Controls namespace. When you drag and drop a Calendar control from the Toolbox to the page, the XAML code will look like the following code where you can see a Calendar XAML element has been added within the Grid element and its Width, Height, Name and VerticalAlignment and HorizontalAlignment attributes are set.

  1. <Grid>  
  2.    <Calendar Height="170" HorizontalAlignment="Left" Margin="58,32,0,0"   
  3.       Name="calendar1" VerticalAlignment="Top" Width="180" />  
  4. </Grid>  

The default view of the Calendar control looks as in Figure 1. 


Figure 1

The Width and Height attributes of the Calendar element represent the width and the height of a Calendar. The Content attribute represents the text of a Calendar. 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 Calendar control and sets the name, height and width properties of a Calendar control. 

  1. <Calendar Name=" MonthlyCalendar" Height="30" Width="100" >  
  2. </Calendar>  

Listing 1

Display Modes

The DisplayMode property of the Calendar class represents the format of the display of a Calendar, that can be a month, year, or decade. Month is the default mode. Setting the DisplayMode to Year and Decade generates Figure 2 and Figure 3 respectively. 


Figure 2


Figure 3


The Month view that is also the default view looks as in Figure 4.


Figure 4

If you use an example of the Decade and click on the year 2008 in Figure 3, you will get another Calendar format with all the months in the year 2008 and if you click on any month, you will eventually get the month view of the Calendar. 

The following code snippet sets the DisplayMode property to Decade. 

  1. <Calendar DisplayMode="Decade">   
  2. </Calendar>  

Selection Modes and Selection Dates

The SelectedDate property represents the currently selected date. If multiple dates selection is true, the SelectedDates property represents a collection of currently selected dates. 

The SelectionMode of type CalendarSelectionMode enumeration represents the selection mode of calendar. Table 1 describes the CalendarSelectionMode enumeration and its members. 
 

CalendarSelectionModeDescription
NoneNo selections are allowed.
SingleDateOnly a single date can be selected, either by setting SelectedDate or the first value in SelectedDates. AddRange cannot be used.
SingleRangeA single range of dates can be selected. Setting SelectedDate, adding a date individually to SelectedDates, or using AddRange will clear all previous values from SelectedDates.
MultipleRangeMultiple non-contiguous ranges of dates can be selected. Adding a date individually to SelectedDates or using AddRange will not clear SelectedDates. Setting SelectedDate will still clear SelectedDates, but additional dates or range can then be added. Adding a range that includes some dates that are already selected or overlaps with another range results in the union of the ranges and does not cause an exception.

The following code snippet sets the SelectionMode property to a single range.

  1. <Calendar SelectionMode="SingleRange">  
  2. </Calendar>  

BlackoutDates

The BlackoutDates property of the Calendar class represents a collection of dates that are not available for selection. All non-selection dates are marked by a cross. For example, say in the month of March of the year 2010, we would like to block the dates from Jan 1st to Jan 7th and then all Sundays and the final calendar should look as in Figure 5.


Figure 5

Part 2 Continuous..

READ MORE

Introduction 

The RichTextBox control allows you to view and edit text, paragraph, images, tables and other rich text format contents. 

The RichTextBox tag represents a RichTextBox control in XAML. 

<RichTextBox></RichTextBox>  

The Width and Height properties represent the width and the height of a RichTextBox. The Name property represents the name of the control, that is a unique identifier of a control. The Margin property tells the location of a RichTextBox on the parent control. The HorizontalAlignment andVerticalAlignment properties are used to set horizontal and vertical alignments. 

The following code snippet sets the name, height and width of a RichTextBox control. The code also sets the horizontal alignment to left and the vertical alignment to top. 

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   

                 VerticalAlignment="Top" Width="500" Height="300" />  

Displaying and Edit Text 

RichTextBox control hosts a collection of RichTextBoxItem. The following code snippet adds items to a RichTextBox control.

   

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"   
             VerticalAlignment="Top" Width="500" Height="300">  
    <FlowDocument>  
        <Paragraph>  
            I am a flow document. Would you like to edit me?  
            <Bold>Go ahead.</Bold>                  
        </Paragraph>  
        
        <Paragraph Foreground="Blue">            
            I am blue I am blue I am blue.    
        </Paragraph>  
    </FlowDocument>          
</RichTextBox> 

The preceding code generates Figure 1 where you can begin editing text right away.

RichTextBox with editable text

Creating and Using RichTectBox Dynamically 

In the previous section, we saw how to create and use a RichTextBox in XAML. WPF provides the RichTextBox class that represents a RichTextBox control. In this section, we will see how to use this class to create and use a RichTextBox control dynamically. 

The code listed in Listing 1 creates a FlowDocument, adds a paragraph to the flow document and sets the Document property of the RichTextBox to FlowDocument.

       


private void CreateAndLoadRichTextBox()  
{  
    // Create a FlowDocument  
    FlowDocument mcFlowDoc = new FlowDocument();  
  
    // Create a paragraph with text  
    Paragraph para = new Paragraph();  
    para.Inlines.Add(new Run("I am a flow document. Would you like to edit me? "));  
    para.Inlines.Add(new Bold(new Run("Go ahead.")));  
  
    // Add the paragraph to blocks of paragraph  
    mcFlowDoc.Blocks.Add(para);  
  
    // Create RichTextBox, set its hegith and width  
    RichTextBox mcRTB = new RichTextBox();  
    mcRTB.Width = 560;  
    mcRTB.Height = 280;  
  
    // Set contents  
    mcRTB.Document = mcFlowDoc;  
  
    // Add RichTextbox to the container  
    ContainerPanel.Children.Add(mcRTB);       
}  

Listing 1

The output of Listing 1 generates Figure 2.

Listing 1 doc

Enable Spelling Check 

RichTextBox control comes with spell check functionality out-of-the-box. By setting theSpellCheck.IsEnabled property to true enables spell checking in a RichTextBox

SpellCheck.IsEnabled="True"  

You can set this in code as follows:

mcRTB.SpellCheck.IsEnabled = true;  

Now if you type some text, the wrong word would be underlined with the Red color. See in Figure 3.

RichTextBox with Spell Check Enabled


Loading a Document in RichTextBox
We can use the RichTextBox.Items.Remove or RichTextBox.Items.RemoveAt methods to delete an item from the collection of items in the RichTextBox. The RemoveAt method takes the index of the item in the collection. 
Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks as in the following:  

private void LoadTextDocument(string fileName)  
{  
    TextRange range;  
    System.IO.FileStream fStream;  
    if (System.IO.File.Exists(fileName))  
    {  
        range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);  
        fStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);  
        range.Load(fStream, System.Windows.DataFormats.Text );  
        fStream.Close();  
    }  
}

READ MORE

The XAML Tooltip element represents a window tooltip. A ToolTip is a pop-up window that displays some information in a small window. This article shows how to use a ToolTip control in WPF.

Creating a ToolTip

The ToolTip element represents a ToolTip control in XAML

<ToolTip/>  

The IsOpen property indicates whether or not a ToolTip is visible. The HorizontalOffset and VerticalOffsetproperties represent the horizontal and vertical distance between the target control and the pop-up window. The Content property represents the contents of the ToolTip. 

The code snippet in Listing 1 creates a ToolTip control and sets the horizontal offset, vertical offset and content of a ToolTip control. 

   

<ToolTip Content="Hello! I am a ToolTip."   
HorizontalOffset="10" VerticalOffset="20"/> 

                                                            Listing 1

The output looks as in Figure 1. 

                                              Creating a ToolTip
                                       

ToolTip Service

To display a tooltip for a control, the ToolTipService class must be used. The SetToolTip and GetToolTipstatic methods are used to set and get the tooltip of a control. 

The following code snippet creates a ToolTipService.ToolTip for a control.

    

<ToolTipService.ToolTip >   
    <ToolTip Content="Hello! I am a ToolTip."   
    HorizontalOffset="10" VerticalOffset="20"/>  
</ToolTipService.ToolTip>   

                           

 <Button Content="Mouse over me" Width="150" Height="30"  
        Canvas.Top="10" Canvas.Left="10">  
    <ToolTipService.ToolTip >   
        <ToolTip Content="Hello! I am a ToolTip."   
        HorizontalOffset="10" VerticalOffset="20"/>  
    </ToolTipService.ToolTip>  
</Button>                                            


Then if you run the application and hover the mouse over the button control, the output looks as in Figure 2.

                                    ToolTip Service
                                                       

Creating a Fancy Tooltip

The ToolTip content can be any control and multiple controls. The code snippet in Listing 4 creates aToolTip with an image and text in it. 

          <!-- Create a button -->  
<Button Content="Mouse over me" Width="150" Height="30"   
        Canvas.Top="50" Canvas.Left="20">  
    <!-- Create a tooltip by using the ToolTipService -->  
    <ToolTipService.ToolTip >  
        <ToolTip HorizontalOffset="0" VerticalOffset="0">  
            <!-- Add a StackPanel to the tooltip content -->  
            <StackPanel Width="250" Height="150">  
                <!-- Add an image -->  
                <StackPanel.Background>  
                    <ImageBrush ImageSource="Garden.jpg"  
                                Opacity="0.4"/>  
                </StackPanel.Background>  
                <!-- Add a text block -->  
                <TextBlock >  
                    <Run Text="This is a tooltip with an image and text"  
                        FontFamily="Georgia" FontSize="14" Foreground="Blue"/>  
                </TextBlock>  
            </StackPanel>  
        </ToolTip>  
    </ToolTipService.ToolTip>  
</Button>                                       


The new tooltip looks as :

                  Creating a Fancy Tooltip
                                     

 

READ MORE

The XAML Toolbar element represents a window toolbar. A ToolBar control is a group of controls that are typically related in functionality. A typical ToolBar is a toolbar in Microsoft Word and Visual Studio where you see File Open, Save and Print buttons. 

This article discusses basic components of ToolBar controls in WPF and how to use them in your applications. 

Creating a Toolbar

The ToolBar element in XAML represents a WPF ToolBar control. 

<ToolBar />  
The code snippet in Listing 1 creates a ToolBar control and sets its width and height properties. You may place any control on a ToolBar but typically buttons are used. A ToolBar sits on a ToolBarTray. The code snippet in Listing 1 adds three buttons to the ToolBar and places a ToolBar on a ToolBarTray.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
  
<ToolBar Name="MyToolbar" Width="200" Height="30" >  
    <Button Background="LightSkyBlue" Content="Open" />  
    <Button Background="LightSkyBlue" Content="Close" />  
    <Button Background="LightSkyBlue" Content="Exit" />  
</ToolBar>  
  
</ToolBarTray>  
                                                      Listing 1


The output looks as in Figure 1. 

         window
                                                      Figure 1

Adding ToolBar Button Click Event Handlers

The best part of WPF is that these buttons are WPF Button controls so you have a choice to use them on any other button. You may format them the way you like. You may add a click event handler to them and so on. 

The code snippet in Listing 2 adds click event handlers to all three ToolBar buttons. 
<ToolBar Name="MyToolbar" Width="200" Height="30"  >  
    <Button Background="LightSkyBlue" Content="Open" Name="OpenButton" Click="OpenButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Close" Name="CloseButton" Click="CloseButton_Click"  />  
    <Button Background="LightSkyBlue" Content="Exit" Name="ExitButton" Click="ExitButton_Click"   />  
 </ToolBar>  
                                                      Listing 2

On these button click event handlers, you would want to write the code you want to execute when these buttons are clicked. For example, I show a message when these buttons are clicked. The code for these button click event handlers is as in Listing 3.
private void OpenButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Open button is clicked.");  
}  
  
private void CloseButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Close button is clicked.");  
}  
  
private void ExitButton_Click(object sender, RoutedEventArgs e)  
{  
    MessageBox.Show("Exit button is clicked.");  
}  
                                                      Listing 3

If you click on the Open button, you will see Figure 2 as output. 

                                    button
                                                      Figure 2

Adding Images to ToolBar Buttons 

Usually ToolBars look nicer than just displaying text. In most cases, they have icons. Displaying an Icon image on a button is simply placing an Image control as the content of a Button. The code snippet in Listing 4 changes the Button contents from text to images. 
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="200" Height="30" Background="LightCoral" >  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 4

The new ToolBar looks as in Figure 3.

                    ToolBar
                                                      Figure 3

Adding Separators to a ToolBar

You may use a Separator control to give your ToolBar buttons a more prominent look. The code snippet in Listing 4 adds a few extra buttons and a few separators to a ToolBar.
<ToolBarTray Background="DarkGray" Height="30" VerticalAlignment="Top">  
    <ToolBar Name="MyToolbar" Width="180" Height="30" Background="LightCoral" >  
        <Separator />  
        <Button Name="OpenButton" Click="OpenButton_Click">  
            <Image Source="Images\camera.png" />  
         </Button>  
        <Button Name="CloseButton" Click="CloseButton_Click">  
            <Image Source="Images\ctv.png" />  
        </Button>  
        <Button Name="ExitButton" Click="ExitButton_Click" >  
            <Image Source="Images\find.png" />  
        </Button>  
        <Separator Background="Yellow" />  
        <Button >  
            <Image Source="Images\award.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\cuser.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\next.png" />  
        </Button>  
        <Button >  
            <Image Source="Images\code.png" />  
        </Button>  
        <Separator />  
    </ToolBar>  
</ToolBarTray>  
                                                      Listing 5

The ToolBar with separators looks as in Figure 4. Also, if you notice there is a drop array that is available when buttons do not fit in a ToolBar. If you click on that, you will see the rest of the buttons.

   
         fit in a ToolBar
                                                      Figure 4

Summary

In this article, I discussed how to use a ToolBar control in WPF and C#.

READ MORE

The XAML TextBlock element represents a text block. The TextBlock control provides a lightweight control for displaying small amounts of flow content. This article shows how to use a TextBlock control in WPF.

Creating a TextBlock

The TextBlock element represents a WPF TextBlock control in XAML. 

  1. <TextBlock/>  

The Width and Height attributes of the TextBlock element represent the width and the height of aTextBlock. The Text property of the TextBlock element represents the content of a TextBlock. The Name attribute represents the name of the control that is a unique identifier of a control. The Foreground property sets the foreground color of contents. This control does not have a Background property. 

The code snippet in Listing 1 creates a TextBlock control and sets the name, height, width, foreground and content of a TextBlock control. Unlike a TextBox control, the TextBlock does not have a default border around it.

<TextBlock Name="TextBlock1" Height="30" Width="200"   

    Text="Hello! I am a TextBlock." Foreground="Red">  

</TextBlock>  

Listing 1

The output looks as in Figure 1

                                          output
                                                      Figure 1

As you can see from Figure 1, by default the TextBlock is placed in the center of the page. We can place aTextBlock control where we want using the MarginVerticalAlignment and HorizontalAlignment attributes that sets the margin, vertical alignment and horizontal alignment of a control. 

The code snippet in Listing 2 sets the position of the TextBlock control in the left top corner of the page. 

<TextBlock Name="TextBlock1" Height="30" Width="200"   
        Text="Hello! I am a TextBlock."   
        Margin="10,10,0,0" VerticalAlignment="Top"   
        HorizontalAlignment="Left">              
</TextBlock>  ​

                                                      Listing 2

Creating a TextBlock Dynamically

The code listed in Listing 3 creates a TextBlock control programmatically. First, it creates a TextBlockobject and sets its width, height, contents and foreground and later the TextBlock is added to theLayoutRoot

private void CreateATextBlock()  
{  
    TextBlock txtBlock = new TextBlock();  
    txtBlock.Height = 50;  
    txtBlock.Width = 200;  
    txtBlock.Text = "Text Box content";  
    txtBlock.Foreground = new SolidColorBrush(Colors.Red);  
  
    LayoutRoot.Children.Add(txtBlock);  
} ​

                                                      Listing 3

Setting Fonts of TextBlock Contents

The FontSizeFontFamilyFontWeightFontStyle and FontStretch properties are used to set the font size, family, weight, style and stretch to the text of a TextBlock. The code snippet in Listing 4 sets the font properties of a TextBlock

  1. FontSize="14" FontFamily="Verdana" FontWeight="Bold"  

                                                      Listing 4

The new output looks as in Figure 4.

                                    hello

READ MORE
...