top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Define and Configure a Grid Control Within a WPF Application Using C#: Part II

+6 votes
379 views

In a previous article, we discovered how to define and configure a Grid control using XAML. In this second article, I'll demonstrate how to do the same task using the code behind, I mean using C#.

Walkthrough:

1. To do so, create a new WPF project

Figure1

2. Right click on the window and select view code, then replace the existing code by this one

public partial class Window1 : Window

    {

        public Window1() {

            InitializeComponent();

            InitializeGrid();

        }

        private void InitializeGrid() {

            Grid oGrid = new Grid();

            oGrid.Width = 200;

            oGrid.Height = 200;

            oGrid.Background = System.Windows.Media.Brushes.Bisque;

            //Set the rows

            RowDefinition Row0 = new RowDefinition();

            RowDefinition Row1 = new RowDefinition();

            RowDefinition Row2 = new RowDefinition();

            //Set the columns

            ColumnDefinition Col0 = new ColumnDefinition();

            ColumnDefinition Col1 = new ColumnDefinition();

            ColumnDefinition Col2 = new ColumnDefinition();          

            //Add the columns and rows to the Grid control

            oGrid.ColumnDefinitions.Add(Col0);

            oGrid.ColumnDefinitions.Add(Col1);

            oGrid.ColumnDefinitions.Add(Col2);

            oGrid.RowDefinitions.Add(Row0);

            oGrid.RowDefinitions.Add(Row1);

            oGrid.RowDefinitions.Add(Row2);

            //Show the grid lines

            oGrid.ShowGridLines = true;

            this.Content = oGrid;

        }
    }


3. Run the project and observe, a window like this will appear, as you see the grid is visible now

 

The Star definition

it means that the related size could be expressed as weighted proportion of available space, for example, if a size of a given first row is double of a second given row size, then the first one will receive two units of the entire grid size, meanwhile, the second one will have one unit as size. Rows and columns sizes are expressed by this symbol * that represents a unit of size. To do so using C# code, use this code snippet. It should be copied and pasted within the scope of InitializeGrid().

private void InitializeGrid(){

            Grid oGrid = new Grid();

            oGrid.Width = 200;

            oGrid.Height = 200;

            oGrid.Background = System.Windows.Media.Brushes.Bisque;

            //Set the rows

            RowDefinition Row0 = new RowDefinition();

            RowDefinition Row1 = new RowDefinition();

            RowDefinition Row2 = new RowDefinition();

            //Set the columns

            /* This code add the star option to resize the

            First row as double of the rest of columns*/

            ColumnDefinition Col0 = new ColumnDefinition();

            Col0.Width = new GridLength(2, GridUnitType.Star);

    

            ColumnDefinition Col1 = new ColumnDefinition();

            ColumnDefinition Col2 = new ColumnDefinition();          

            //Add the columns and rows to the Grid control

            oGrid.ColumnDefinitions.Add(Col0);

            oGrid.ColumnDefinitions.Add(Col1);

            oGrid.ColumnDefinitions.Add(Col2);

            oGrid.RowDefinitions.Add(Row0);

            oGrid.RowDefinitions.Add(Row1);

            oGrid.RowDefinitions.Add(Row2);

            //Show the grid lines

            oGrid.ShowGridLines = true;

            this.Content = oGrid;

        }

Run the project and the result will be

 

The Pixel definition

It means that the size is defined in terms of pixels such as in the ASP applications. This bellow C# code illustrates how to define a dimension of a given column or row based on pixels.

private void InitializeGrid() {

            Grid oGrid = new Grid();

            oGrid.Width = 200;

            oGrid.Height = 200;

            oGrid.Background = System.Windows.Media.Brushes.Bisque;

            //Set the rows

            RowDefinition Row0 = new RowDefinition();

            RowDefinition Row1 = new RowDefinition();

            RowDefinition Row2 = new RowDefinition();

            //Set the columns

            /* This code add the pixel option to resize the

            First row as double of the rest of columns*/

            ColumnDefinition Col0 = new ColumnDefinition();

            Col0.Width = new GridLength(50, GridUnitType.Pixel);    

            ColumnDefinition Col1 = new ColumnDefinition();

            ColumnDefinition Col2 = new ColumnDefinition();          

            //Add the columns and rows to the Grid control

            oGrid.ColumnDefinitions.Add(Col0);

            oGrid.ColumnDefinitions.Add(Col1);

            oGrid.ColumnDefinitions.Add(Col2);

            oGrid.RowDefinitions.Add(Row0);

            oGrid.RowDefinitions.Add(Row1);

            oGrid.RowDefinitions.Add(Row2);

            //Show the grid lines

            oGrid.ShowGridLines = true;

            this.Content = oGrid;

        }

posted Nov 25, 2015 by Jdk

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


Related Articles

In this article, I will try to make a representation of the Grid object witch is directly derived from the Panel abstract class and we can say that is a flexible area that contains rows and columns, it plays a role of container in a given WPF window. The grid could be found in the PresentationFramework assembly. The grid control could be used to create a complex layout that gives to the application an attractive and ergonomic look. So let's discover how to configure it using XAML in this part and in second part I will illustrate how to perform the same task using the code behind, I mean C#.

At first look, when a new WPF application is defined, we have the impression that there is not controls but the window one, even if the "<Grid></Grid>" tags are presents, and the first question that one can ask is where are the grid lines if it is a grid really? 

 

Figure 1

I tell you ok try this code:

<Grid ShowGridLines="True">

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

I use the <Grid.RowDefinitions> to define a collection of rows and a<Grid.ColumnDefinitions> to define columns collection. In the other hand I use<RowDefinition> to define a row element within the grid control and <ColumnDefinition> to define a column element, and then I set ShowGridLines property to true, it is very important in order to render columns and rows visible. The result will be as follows:

Figure 2

The columns and rows definition mode could be, namely star, Auto or Pixel.

The Star definition

It means that the related size could be expressed as weighted proportion of available space, for example if a size of a given first row is double of a second given row size, then the first one will receive two units of the entire grid size, meanwhile, the second one will have one unit as size. Rows and columns sizes are expressed by this symbol * that represents a unit of size. The XAML code sample illustrates how to define a size based on star definition.

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="2*"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The result of the above code is:

Figure 3

The above code sets the first column width as double of the reset of the columns.

The Pixel definition

It means that the size is defined in terms of pixels such as in the ASP applications. This bellow code illustrate how to define a dimension of a given column or row based on pixels

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="100px"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

And this is a presentation of what could be if such alternative is used

Figure 4

The Auto definition

It means that the size is proportional to the content object size. Once the column or the row width or height is set to auto and there is no object contained with it. It disappears from the grid but it doesn't mean that it is deleted. If you add controls within, it takes exactly the control dimension. For example, if we make a rectification of the previous code

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The grid appearance will be

Figure 5

Cut  Width="Auto"  then drag and drop a button into the grid and make sure that it is contained within the row 0 , column 0 grid cellule and this is the XAML button code.

<Button Grid.Column="0" Grid.Row="0" Width="100" Name="button1">Button</Button>

Now, paste Width="Auto" exactly in its previous place and you will observe this. As you see the button is clipped rather that scrolled.

Figure 6

 

READ MORE

Before Continue to read our first article How to use a TextBlock in WPF and windows phone application Part-1?

http://tech.queryhome.com/94985/how-use-textblock-xaml-wpf-and-windows-phone-application-part

The FontSource property allows loading custom fonts dynamically. The following code snippet sets theFontSource property. 

Uri fontUri = new Uri("SomeFont.ttf", UriKind.Relative);  

StreamResourceInfo MySRI = Application.GetResourceStream(fontUri);  

TextBlock1.FontSource = new FontSource(MySRI.Stream);  

Wrapping, Alignment and Padding 

The TextWrapping property sets the wrap of no wrap text. The following code snippet sets the wrapping text option. 

TextWrapping="Wrap"  

The TextAlignment property sets the text alignment in a TextBlock that is of type TextAlignmentenumeration. A text can be aligned left, center, or right. 

TextAlignment="Right"  

The Padding property sets the space between a boundary and the text that can be applied to all sides or a selected side of the boundary. The padding spacing is based on left, right, top and bottom. If you specify only a single value, the padding will be applied to all four sides and if you specify two values, it will be applied to LeftTop and BottomRight sides. 

Listing 5 shows all these properties in a complete sample.

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

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

    Margin="10,10,0,0" VerticalAlignment="Top"   

    HorizontalAlignment="Left"  

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

    TextWrapping="Wrap" TextAlignment="Center" Padding="2">  

</TextBlock>  

                                                      Listing 5

Inlines

The Inlines property represents the collection of inline text within a TextBlock control. A Run object represents an inline text and can be treated as its own text control and have its foreground and font related properties. 

Listing 6 sets the Inlines property of the TextBlock and sets various fonts and foreground colors. 

<TextBlock.Inlines>  

    <Run FontWeight="Bold" FontSize="14" Text="Hi! I am a TextBlock. " />   

    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />  

    <Run FontStyle="Italic" FontSize="18" Text="Here is some linear gradient text. ">  

        <Run.Foreground>  

            <LinearGradientBrush>   

                <GradientStop Color="Green" Offset="0.0" />   

                <GradientStop Color="Purple" Offset="0.25" />   

                <GradientStop Color="Orange" Offset="0.5" />   

                <GradientStop Color="Blue" Offset="0.75" />   

              </LinearGradientBrush>   

        </Run.Foreground>  

    </Run>              

    <Run FontStyle="Italic" Foreground="Green" Text="How about adding some green? " />              

</TextBlock.Inlines>  

                                                      Listing 6

The new output looks as in Figure 5.

                    new output looks
                                                      Figure 5

TextDecorations

The TextDecorations property represents the text decorations that are applied to the content of aTextBlock. WPF supports only underlined text decoration. 

Listing 7 sets the TextDecorations to underline. 

<TextBlock Name="TextBlock1"        

    Margin="10,10,0,0" VerticalAlignment="Top"   

    HorizontalAlignment="Left"  

    FontSize="12" FontFamily="Verdana"   

    TextWrapping="Wrap" TextAlignment="Left" Padding="2"  

           TextDecorations="Underline">  

                                                      Listing 7

The new output looks as in Figure 6.

              new output looks like
                                                      Figure 6

Summary

In this article, I discussed how to create and format a TextBlock control in WPF and C#. Then we saw how to create a TextBlock control dynamically. Then we saw how to set various properties of a TextBlock such as fonts, Inlines and text decorations.

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

Read our first Article How to use a TabControl in WPF and windows phone application Part-1?http://tech.queryhome.com/93377/how-to-use-tabcontrol-wpf-and-windows-phone-application-part#rHE29pyoFe3gKBoS.99
 

Listing 2
If I run the application, the Circle tab shows me a circle that looks as in Figure 3.

 

Figure 3
If I click on Rectangle and Polygon, the output looks as in Figure 4 and Figure 5 respectively. 

 

Figure 4

 

Figure 5
Formatting Tab Items 

Let's get a little creative. How about making our tab headers and tab control areas look nicer. 

In a Tab Control, both a Tab Header and Tab Item are loosely coupled and we can treat them as any otherWPF control. That said, we can place any children controls on them, format them and do whatever we want. So if we want to place a DataGrid control in a TabItem header, we can do that. 

Now let's format our Tab Item Header and Tab Item container area. We will format our Tab Item that looks as in Figure 6, where we will use multiple colors for the background and change the text of the Tab Item Header and we will also change the background of the Tab Item container area to a gradient background. 


 

Figure 6
To do this, I placed a StackPanel on TabItem.Header and set its background to a LinearGradientBrush. Then, I placed an Ellipse and a TextBlock on the TabItem Header. 

Then as the content of the TabItem, I placed a StackPanel and changed its background to aLinearGradientBrush. See Listing 3. 

​     <TabItem >  
        <!-- Create Tab Header -->  
        <TabItem.Header>  
            <!-- Place a StackPanel on TabHeader so we can place multiple controls on it -->  
            <StackPanel Orientation="Horizontal">  
                <StackPanel.Background>  
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0" >  
                        <LinearGradientBrush.GradientStops>  
                            <GradientStop Offset="0" Color="Orange"/>  
                            <GradientStop Offset="0.25" Color="Purple"/>  
                            <GradientStop Offset="0.5" Color="Violet"/>  
                            <GradientStop Offset="0.75" Color="Green"/>  
                        </LinearGradientBrush.GradientStops>  
                    </LinearGradientBrush>  
                </StackPanel.Background>                                  
                <Ellipse Height="20" Width="20" Stroke="Black" StrokeThickness="2" Fill="Yellow"/>  
                <TextBlock Text="Circle" Margin="1,1,1,1" VerticalAlignment="Center"  
                           FontFamily="Georgia" FontSize="18" FontWeight="Bold" />  
            </StackPanel>  
        </TabItem.Header>  
      
        <!-- Place a StackPanel on TabItem to place children controls -->  
        <StackPanel>  
            <StackPanel.Background>  
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >  
                    <LinearGradientBrush.GradientStops>  
                        <GradientStop Offset="0" Color="Orange"/>  
                        <GradientStop Offset="0.25" Color="Purple"/>  
                        <GradientStop Offset="0.5" Color="Violet"/>  
                        <GradientStop Offset="0.75" Color="Green"/>  
                    </LinearGradientBrush.GradientStops>  
                </LinearGradientBrush>  
            </StackPanel.Background>  
            <Ellipse Height="100" Width="100" StrokeThickness="5" Stroke="black" Fill="gold"/>  
        </StackPanel>  
    </TabItem >   
 

Listing 3

Note: If you would like to load images at the top of text of the header, simply remove Orientation="Horizontal" from the stack panel in the preceding code. The default orientation is vertical. 

 

NOTE: Part-3 will update soon..

READ MORE

Tab Control has tab items and each tab item represents a container that is used to host other controls. A typical example of a Tab control is the Visual Studio designer as shown in Figure 1. If you click on theWindow1.xaml tab item, you will see XAML code but if you click on Window1.xaml.cs, you will see C# code behind. 


Figure 1

Create a Tab Control


The TabControl element in XAML represents a Tab Control. 

  1. <TabControl />  

The code snippet in Listing 1 creates a Tab Control and sets it height, width, margin and alignment. The code also adds a TabItem

  1. <TabControl Height="238" HorizontalAlignment="Left" Margin="12,12,0,0"   
  2.             Name="tabControl1" VerticalAlignment="Top" Width="445">  
  3.     <TabItem Header="tabItem1" Name="tabItem1">  
  4.     </TabItem>  
  5. </TabControl>  

Listing 1

The output of Listing 1 looks as in Figure 2.


Figure 2

Adding Tab Items

Tab Control is nothing without a Tab Item. The <TabItem \> element in XAML represents a Tab Item. The Header property of a TabItem represents the header text of the header. The following code creates aTabItem with the header text “Circle”.

          <TabItem Header="Circle">   

             </TabItem>  

A tab item can host other XAML controls similar to a panel or grid control. For example, the following code adds a StackPanel to the tab item and on that StackPanel, it creates a circle with height and width 100. 

 
<TabItem  Header="Circle">  
   <StackPanel>  
<Ellipse Height="100" Width="100" StrokeThickness="5" Stroke="black"  
      Fill="gold"/>  
   </StackPanel>  
</TabItem > 

Using the same preceding approach, I add three tab items to the tab control (Listing 2) called Circle, Rectangle and Polygon. 

<TabControl Height="150" FontFamily="Verdana" FontSize="12" >  
            <TabControl.Background>  
                <SolidColorBrush Color="Green" Opacity="0.30"/>  
            </TabControl.Background>  
            <TabItem  Header="Circle">  
                <StackPanel>  
                    <Ellipse Height="100" Width="100" StrokeThickness="5" Stroke="black"  
      Fill="gold"/>  
                </StackPanel>  
            </TabItem >  
            <TabItem  Header="Rectangle">  
                <StackPanel>  
                    <Rectangle Fill="Yellow" Width="100" Height="100" Stroke="Blue" StrokeThickness="5">  
                    </Rectangle>  
                </StackPanel>  
            </TabItem >  
            <TabItem  Header="Polygon">  
                <StackPanel>  
                    <Polygon Points="100,50 50,100 150,100 100,50 100,30"  
       Stroke="green" StrokeThickness="3" Fill="Yellow"/>  
                </StackPanel>  
            </TabItem >  
</TabControl>  

Listing 2


Part 2: http://tech.queryhome.com/94066/how-to-use-tabcontrol-wpf-and-windows-phone-application-part

READ MORE

Data Binding with Controls

The last data binding type we will see is how to provide a data exchange between a ListBox and other controls using data binding in WPF.

We will create an application that looks as in Figure 12. In Figure 12, I have a ListBox with a list of colors, a TextBox and a Canvas. When we pick a color from the ListBox, the text of TextBox and color of Canvas changes dynamically to the color selected in the ListBox and this is possible to do all inXAML without writing a single line of code in the code behind file.

looks like Figure
                                                Figure 12.

The XAML code of the page looks as in following.

​       <StackPanel Orientation="Vertical">  
    <TextBlock Margin="10,10,10,10" FontWeight="Bold">  
        Pick a color from below list  
    </TextBlock>  
    <ListBox Name="mcListBox" Height="100" Width="100"  
             Margin="10,10,0,0" HorizontalAlignment="Left" >  
        <ListBoxItem>Orange</ListBoxItem>  
        <ListBoxItem>Green</ListBoxItem>  
        <ListBoxItem>Blue</ListBoxItem>  
        <ListBoxItem>Gray</ListBoxItem>  
        <ListBoxItem>LightGray</ListBoxItem>  
        <ListBoxItem>Red</ListBoxItem>  
    </ListBox>   
   <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left"  >  
        <TextBox.Text>  
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
        </TextBox.Text>  
    </TextBox>  
    <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left" >  
        <Canvas.Background>  
            <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
        </Canvas.Background>  
    </Canvas>  
</StackPanel>        

If you look at the TextBox XAML code, you will see the Binding within the TextBox.Text property that sets the binding from TextBox to another control and another control ID is ElementName and another control's property is Path. So in the following code, we are setting the SelectedItem.Content property ofListBox to the TextBox.Text property. 

 <TextBox.Text>  

   <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
</TextBox.Text>  

Now the same applies to the Canvas.Background property, where we set it to theSelectedItem.Content of the ListBox. Now, every time you select an item in the ListBox, theTextBox.Text and Canvas.Background properties are set to that selected item in the ListBox.


<Canvas.Background>  
   <Binding ElementName="mcListBox" Path="SelectedItem.Content"/>  
</Canvas.Background> 

Summary

In this article, I explained how to create and use a ListBox control available in WPF and WP8. We saw how to add items to a ListBox, change item properties and add images add check boxes. In the end of this article, we saw how data binding works in ListBox and how to bind a ListBox with data coming from objects, databases and other controls. 

READ MORE

Now we add a ListBox control and set its ItemsSource property as the first DataTable of the DataSetand set ItemTemplate to the resource defined above. 

<ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}"  ItemTemplate="{StaticResource listBoxTemplate}" />  

Now in our code behind, we define the following variables. 

public SqlConnection connection;  

public SqlCommand command;  

string sql = "SELECT ContactName, Address, City, Country FROM Customers"

string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"

Now on the Windows_Loaded method, we call the BindData method and in the BindData method, we create a connection, data adapter and fill in the DataSet using the SqlDataAdapter.Fill() method.

private void Window_Loaded(object sender, RoutedEventArgs e)  
{  
    BindData();             
}  
  
private void BindData()  
{  
    DataSet dtSet = new DataSet();  
    using (connection = new SqlConnection(connectionString))  
    {  
        command = new SqlCommand(sql, connection);                 
        SqlDataAdapter adapter = new SqlDataAdapter();             
        connection.Open();  
        adapter.SelectCommand = command;  
        adapter.Fill(dtSet, "Customers");  
        listBox1.DataContext = dtSet;  
    }  
}  

Data Binding with XML 

Now let's look at how to bind XML data to a ListBox control. The XmlDataProvider is used to bind XMLdata in WPF

Here is an XmlDataProvider defined in XAML that contains books data. The XML data is defined within the x:Data tag. 

       

<XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">  
    <x:XData>  
        <Inventory xmlns="">  
            <Books>  
                <Book Category="Programming" >  
                    <Title>A Programmer's Guide to ADO.NET</Title>  
                    <Summary>Learn how to write database applications using ADO.NET and C#.  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Graphics Programming with GDI+</Title>  
                    <Summary>Learn how to write graphics applications using GDI+ and C#.  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>Addison Wesley</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Visual C#</Title>  
                    <Summary>Learn how to write C# applications.  
                    </Summary>  
                    <Author>Mike Gold</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Programming" >  
                    <Title>Introducing Microsoft .NET</Title>  
                    <Summary>Programming .NET  
                    </Summary>  
                    <Author>Mathew Cochran</Author>  
                    <Publisher>APress</Publisher>  
                </Book>  
                <Book Category="Database" >  
                    <Title>DBA Express</Title>  
                    <Summary>DBA's Handbook  
                    </Summary>  
                    <Author>Mahesh Chand</Author>  
                    <Publisher>Microsoft</Publisher>  
                </Book>  
            </Books>  
        </Inventory>  
    </x:XData>  
</XmlDataProvider>  

To bind an XmlDataProvider, we set the Source property inside the ItemsSource of a ListBox to thex:Key of XmlDataProvider and XPath is used to filter the data. In the ListBox.ItemTempate, we use the Binding property. 

<ListBox Width="400" Height="300" Background="LightGray">  
    <ListBox.ItemsSource>  
        <Binding Source="{StaticResource BooksData}"  
       XPath="*[@Category='Programming'] "/>  
    </ListBox.ItemsSource>  
  
    <ListBox.ItemTemplate>  
        <DataTemplate>  
            <StackPanel Orientation="Horizontal">  
                <TextBlock Text="Title: " FontWeight="Bold"/>  
                <TextBlock Foreground="Green"  >  
                    <TextBlock.Text>   
                        <Binding XPath="Title"/>  
                    </TextBlock.Text>                        
                </TextBlock>                       
           </StackPanel>  
        </DataTemplate>  
    </ListBox.ItemTemplate>  
</ListBox>  

The output of the preceding code looks as in Figure 11.

code behind file

 

READ MORE
...