top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Bind The Visibility Of A Control Based On The Property Of RadioButton or CheckBox

+1 vote
456 views

If you want to control the visibility of a control like textblock/textbox, etc. based on the Checked or Unchecked Property of RadioButton/Checkbox , then you can use the inbuilt ‘BooleanToVisibilityConverter’ to achieve this easily. This will prevent you to write longer codes to control the visibility from CodeBehind pages. This is useful, for example, when you want to hide a certain control when a checkbox is checked and hide that control when the checkbox is unchecked.

Steps:

  1. First of all define the following code inside the <Application.Resources> </Application.Resources>tag of the App.XAML page.
    1. <local:BooleanToVisibilityConverter x:Key="MyConverter1"/>  
    code

    It is necessary to provide a key to this converter. I have given it a key of MyConverter1 . We will access this converter by using this Key from this point onwards.
     
  2. Now suppose, I have a Checkbox Control as in the following snippet whose Name isMyCheckBoxControl
    <CheckBox x:Name="MyCheckBoxControl" Content="My Check Box”/>
     .
     
  3. Similarly I have a TextBox which I want to make visible only when the CheckBox above is checked, i.e whenever IsChecked property of CheckBox is set to ‘True’. We will bind the TextBox control to the CheckBox as in the following code snippet:
    1. <TextBox x:Name="MyTextBox" Visibility="{Binding ElementName=MyCheckBox,Path=IsChecked,Converter={StaticResource MyConverter1}}" />  
    TextBox

    Here, the Visibility Property of the TextBox is binded to an ‘ElementName=MyCheckBox’ which is our Checkbox name. The ‘Path=IsChecked’ is the property which we want to be true in order to hide the TextBox and the ‘Converter={StaticResource MyConverter1}’ is the Converter that we implement to hide our TextBox.

    This gets our job done without even having to visit the CodeBehind pages.

How the Converter Works and why it is necessary?

We know, a ‘Visibility’ property only takes its value as either Visiblity.Visible or Visibility.Collapsed.
And we also know that a ‘checkbox’(or a RadioButton)’s IsChecked Property only takes its value as either ‘true’ or ‘false’.

Since a visibility property cannot take ‘true’ or ‘false’ value, so in order to assign the Visibility property’s value as Visibility.Visible or Visibility.Collapsed based on either ‘true’ or ‘false’ property of the CheckBox, we need a Converter. This Converter as its name implies converts the ‘true’ value to ‘Visibility.Visible’ and ‘false’ value to ‘Visibility.Collapsed’ and hence allows the binding to happen easily

posted Mar 22, 2016 by Jdk

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


Related Articles

 

Introduction

The purpose of this sample is to show how to bind a Dictionary a Lisbox in apps based in XAML, using the MVVM pattern.

Building the Sample

You only need Visual Studio 2012/2013 running in Windows 7, 8, 8.1 or later.

Description

Suppose we have a resource dictionary with some data that we need to show in an application and for each item in a Listbox, we want to show the key/value.

We will start by creating a model class called "Company" that has only two properties: Name and URL.
C#
/// <summary>   
/// Define the Company.   
/// </summary>   
public class Company   
{   
    /// <summary>   
    /// Gets or sets the name.   
    /// </summary>   
    /// <value>The name.</value>   
    public string Name { get; set; }   
  
    /// <summary>   
    /// Gets or sets the URL.   
    /// </summary>   
    /// <value>The URL.</value>   
    public string Url { get; set; }   

In the MainViewModel we will create the resource dictionary where the Company is the key and the value will be an int and we will have a SelectedCompany property to get the company selected in the listbox.

The MainViewModel will be defined by:

C#

public class MainViewModel : ViewModelBase   
{   
   private Company _selectedCompany;   
  
   /// <summary>   
   /// Initializes a new instance of the MainViewModel class.   
   /// </summary>   
   public MainViewModel()   
   {   
      Companies = new Dictionary<Company, int>   
      {   
         {   
            new Company   
            {   
               Name = "Microsoft", Url="www.microsoft.com"   
            }, 1   
         },   
         {   
            new Company   
            {   
               Name = "Google", Url="www.google.com"   
            }, 2   
         },   
         {   
            new Company   
            {   
               Name = "Apple", Url="www.apple.com"   
            }, 3   
         }   
      };   
   }   
  
   /// <summary>   
   /// Gets or sets the selected company.   
   /// </summary>   
   /// <value>The selected company.</value>   
   public Company SelectedCompany   
   {   
      get { return _selectedCompany; }   
      set { Set(() => SelectedCompany, ref _selectedCompany, value); }   
   }   
  
   /// <summary>   
   /// Gets or sets the companies.   
   /// </summary>   
   /// <value>The companies.</value>   
   public Dictionary<Company, int> Companies { get; set; }   
}  

The MainWindow will defined as in the following:


XAML

 

<mui:ModernWindow x:Class="BindingResourceDictionarySample.MainWindow"   
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
                  xmlns:mui="http://firstfloorsoftware.com/ModernUI"   
                  Title="Sample"   
                  Width="525"   
                  Height="350"   
                  DataContext="{Binding Main,   
                                        Source={StaticResource Locator}}"   
                  Style="{StaticResource BlankWindow}">   
    <StackPanel>   
        <TextBlock Margin="20,20,0,0" Text="How to binding a Dictionary to a Listbox" />   
        <ListBox Width="250"   
                 Margin="20,20,0,0"   
                 HorizontalAlignment="Left"   
                 ItemsSource="{Binding Companies}"   
                 SelectedValue="{Binding ItemIndex}"   
                 SelectedValuePath="Key"   
                 SelectionMode="Single">   
            <ListBox.ItemTemplate>   
                <DataTemplate>   
                    <Border Width="245"   
                            BorderBrush="Orange"   
                            BorderThickness="2">   
                        <StackPanel Orientation="Horizontal">   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Value}" />   
                            <TextBlock Margin="20,0,0,0" Text="{Binding Path=Key.Name}" />   
                        </StackPanel>   
                    </Border>   
                </DataTemplate>   
            </ListBox.ItemTemplate>   
        </ListBox>   
    </StackPanel>   
</mui:ModernWindow>

To get the selected Company the SelectedValue property from the Listbox will be used that will use the SelectedValuePath to understand which value to return. To get the value instead of the Company we should change the Key to Value.

Note:   

  1. To have a nice look, we will use the ModernWindow from the ModernUI (for WPF). For more see the ModerUI in Modern UI Samples.
     
  2. The sample is similar to any XAML app, where we show the UI for WPF.

Running the sample
 

binding a dictonary


Source code files:

 

  • ViewModelLocator class contains static references to all the view model in the application and provide an entry point for the bindings.
     
  • MainViewModel class for binding to MainView.xaml
     
  • MainWindow represents the view.
     
  • Company defines the model.
READ MORE
 

The great thing about XAML is that you can easily change the foreground colour of controls, such as a TextBlock, to be exactly what you want it to be. Whether that is through the built-in colour names or a HEX colour is completely your choice.

 

However there may be times when you simply wish to change the colour of a control dependent on the value that it is displaying. In this example we will be using a TextBlock that has it's Text value assigned to it using data context binding.

 

MainPage.xaml

<Page        
    x:Class="MainPage"    
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    xmlns:local="using:TestProject"    
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        
    mc:Ignorable="d">    
    <Page.Resources>    
        <DataTemplate x:Key="listViewItems">    
            <StackPanel>    
                <TextBlock        
                    Margin="5,5,5,5"        
                    Text="{Binding Name}"        
                    Style="{StaticResource BaseTextBlockStyle}"/>    
                <TextBlock        
                    Margin="5,5,5,5"        
                    Text="{Binding Ripeness}"        
                    Style="{StaticResource BaseTextBlockStyle}"/>    
            </StackPanel>    
        </DataTemplate>    
    </Page.Resources>    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">    
        <ListView        
            x:Name="listViewTest"        
            Margin="5,5,5,5"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Center"        
            ItemsSource="{Binding}"        
            SelectionMode="None"        
            IsItemClickEnabled="False"        
            ItemTemplate="{StaticResource listViewItems}"        
            ContainerContentChanging="listViewUpdated"></ListView>    
        <TextBlock        
            x:Name="listViewNoItems"        
            Margin="5,5,5,5"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Center"        
            Text="There are no fruits in your list to display!"        
            Style="{StaticResource BaseTextBlockStyle}"        
            Visibility="Collapsed"/>    
        <Button        
            Width="150"        
            Height="50"        
            Margin="20"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Right"        
            Content="Clear fruit"        
            Click="clearFruitBasket"/>    
    </Grid>    
</Page>  

 

MainPage.xaml.cs


using System.Collections.ObjectModel;    
using Windows.UI.Xaml;    
using Windows.UI.Xaml.Controls;    
namespace CSharpCornerTestProject     
{    
    public class Fruit     
    {    
        public string Name    
        {    
            get;    
            set;    
        }    
        public string Ripeness     
        {    
            get;    
            set;    
        }    
    }    
    public sealed partial class MainPage: Page     
    {    
        private ObservableCollection < Fruit > fruitList = new ObservableCollection < Fruit > ();    
        public MainPage()     
        {    
            this.InitializeComponent();    
            fruitList.Add(new Fruit()    
            {    
                Name = "Apple", Ripeness = "Ok"    
            });    
            fruitList.Add(new Fruit()    
            {    
                Name = "Banana", Ripeness = "Bad"    
            });    
            fruitList.Add(new Fruit()    
            {    
                Name = "Kiwi", Ripeness = "Rotten"    
            });    
    
            listViewTest.ItemsSource = fruitList;    
        }    
        private void listViewUpdated(ListViewBase sender, ContainerContentChangingEventArgs args) {    
            if (listViewTest.Items.Count == 0)     
            {    
                listViewNoItems.Visibility = Visibility.Visible;    
                listViewTest.Visibility = Visibility.Collapsed;    
            }     
            else     
            {    
                listViewNoItems.Visibility = Visibility.Collapsed;    
                listViewTest.Visibility = Visibility.Visible;    
            }    
           }    
        private void clearFruitBasket(object sender, RoutedEventArgs e)    
        {    
            // clear the fruit list!        
            if (fruitList != null) fruitList.Clear();    
        }    
    }    
}

As I stated above, this is the code base that we used in my previous article about displaying a message once a ListView control no longer has any items in it. We will slightly modify this now so that the ripeness of the fruit in our fruit basket is colour-coded depending on its value.

 

The first thing we need to do is to create a convertor class for us to use when binding data to the list view. This is a very simple affair and just requires you to add a new "Class file" to your project.

 

FruitBasketConvertor.cs

using System;    
using Windows.UI;    
using Windows.UI.Xaml.Data;    
using Windows.UI.Xaml.Media;    
namespace CSharpCornerTestProject.Convertors     
{    
    public class fruitBasketRipenessForegroundConvertor: IValueConverter    
    {    
        public object Convert(object value, Type targetType, object parameter, string language)    
        {    
            string ripeness = (value as string);    
            if (ripeness == "Ok") return new SolidColorBrush(Colors.ForestGreen);    
            else if (ripeness == "Bad") return new SolidColorBrush(Colors.OrangeRed);    
            else if (ripeness == "Rotten") return new SolidColorBrush(Colors.DarkRed);    
            // default return value of lime green      
            return new SolidColorBrush(Colors.LimeGreen);    
        }    
        public object ConvertBack(object value, Type targetType, object parameter, string language)    
        {    
            throw new NotImplementedException();    
        }    
    }    
}  

That is all there is to our file, just those 30 lines. Do take note, however, that we have placed the convertors under their own namespace, CSharpCornerTestProject.Convertors.

 

Using convertors isn't all as daunting as it seems. You create your own custom class, making sure that it derives from IValueConvertor.  Then all we need are two functions.

public object Convert(object value, Type targetType, object parameter, string language)  
{  
    // your convertor code goes here    
}  
public object ConvertBack(object value, Type targetType, object parameter, string language)   
{  
    // your convert back code goes here    
}

The Convert function takes the raw value of your binding and allows you to access anything associated with that, whether it is a class, a string, or anything of your choosing.

 

The ConvertBack function is generally not used all that often and so in our example we are leaving it asthrow new NotImplementedException();. Its main use would be if you wanted to convert the value back to its original state.

 

Returning to the Convert function, this is very simple and there isn't all that much to it at all. All we do here is take the object value and store it into our string variable, ripeness.  

public object Convert(object value, Type targetType, object parameter, string language)   
{  
    string ripeness = (value as string);  
    if (ripeness == "Ok") return new SolidColorBrush(Colors.ForestGreen);  
    else if (ripeness == "Bad") return new SolidColorBrush(Colors.OrangeRed);  
    else if (ripeness == "Rotten") return new SolidColorBrush(Colors.DarkRed);  
    // default return value of lime green      
    return new SolidColorBrush(Colors.LimeGreen);  
}   

Since we have different forms of Ripeness in our Fruit class, we have three separate if statements to determine which colour we should return for our Foreground colour.

 

When converting a Foreground (or Background) XAML member, it expects a SolidColorBrush to be returned and so that is what we are giving it.

 

That is everything that we need to do for the code side of things with our convertor, the next step is much simpler and only requires us to add three new lines of code to the existing MainPage.xaml file that we have.

 

In our Page control, we need to add a new member, highlighted in bold Green.

<Page  
x:Class="MainPage"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="using:rTestProject"  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    xmlns:utils="using:TestProject.Convertors"  
mc:Ignorable="d">  

This will allow us to access the custom convertor class that we just created in FruitBasketConvertor.cs.

 

Now that we have done that, we need to add our convertor function as a page resource and provide it a key. This will allow us to access it when using the binding convertor. Once again, the addition is highlighted in bold Green.

<Page.Resources>  
    <utils:fruitBasketRipenessForegroundConvertor x:Key="ripenessConvertor"/>  
    <DataTemplate x:Key="listViewItems">  
        <StackPanel>  
            <TextBlock      
                Margin="5,5,5,5"      
                Text="{Binding Name}"      
                Style="{StaticResource BaseTextBlockStyle}"/>  
            <TextBlock      
                Margin="5,5,5,5"      
                Text="{Binding Ripeness}"      
                Style="{StaticResource BaseTextBlockStyle}"/>  
        </StackPanel>  
    </DataTemplate>  
</Page.Resources>

Now that we have given our convertor a key, we can access it anywhere in the MainPage.xaml file when we are binding items. We just have one last thing to do now, that is to add a Foreground member to the TextBlock control that is telling us how ripe our fruit is.

<TextBlock    
    Foreground="{Binding Ripeness, Converter={StaticResource ripenessConvertor}}"    
    Margin="5,5,5,5"    
    Text="{Binding Ripeness}"    
    Style="{StaticResource BaseTextBlockStyle}"/>    

That is everything that we need to do to start dynamically changing the foreground colour of our XAML controls dependent on what the value they're displaying is. If you run the app your fruit basket should now show the Ripeness of each fruit in the three different colours that we assigned earlier on whilst creating our convertor function.

 

READ MORE

Introduction:

  1. Open Visual Studio 2008 and create a new project, a WPF application and name it myWpfApplication



    Figure1
     
  2. The new WPF form called Window1 appears in addition to the XAML code editor



    Figure 2
     
  3. Expand the project node in the solution explorer and right click the references menu item, then click add reference context menu item.



    Figure 3
     
  4. Select the .Net tab then add WindowsFormsIntegration assembly reference to the solution. 



    Figure 4
     
  5. Then add another reference, it will be  our well known Windows forms assembly



    Figure 5
     
  6. Now, as the references are added, switch to the C# code by right clicking the Window1 and clicking the view code context menu item

    Do add the two namespaces 

    using System.Windows.Forms;
    using System.Windows.Forms.Integration;
     
  7. Expand the toolbox and go to the bottom, you find there an element witch called WindowsFormHost
     
  8. Drag and drop it into the WPF window or simply add this couple of lines of XAML code into the XAML editor
     

    <my:WindowsFormsHost Margin="18,20,38,73" Name="windowsFormsHost1">

              

    </my:WindowsFormsHost>
     
  9. Take a look on the XAML code, it will look like this
     

    <Window x:Class="myWpfApplication.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

        Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

             Loaded="Window_Loaded">

        <Grid>

            <WindowsFormsHost Height="100" Margin="39,27,39,0" Name="windowsFormsHost1"   VerticalAlignment="Top" >

               

            </WindowsFormsHost>

     

        </Grid>

    </Window>
     
  10. Within the WindowsFormHost tag, add those lines:
     

    <WindowsFormsHost Height="100" Margin="39,27,39,0" Name="windowsFormsHost1"VerticalAlignment="Top" >

      <wf:ElementHost BackColor="Beige">

        <Button Background="Bisque" Margin="39,27,39,27" Click="Button_Click">Click me  please!</Button>

      </wf:ElementHost>

    </WindowsFormsHost>
     
  11. Now, switch to the code behind zone, you find there the button click event handler  related stub, then implement it as follows
     

    private void Button_Click(object sender, RoutedEventArgs e)

    {

      System.Windows.Forms.MessageBox.Show("My parent is the hosted window form","Message");

    }
     
  12. Do run the application and observe

    wpf6.gif

    Figure 6
READ MORE

The ScrollViewer is an object that represents a scrollable area that contains other visible controls, it could be found within the System.Windows.Controls.  At the contrast of a ScrollBar object, the ScrollViewer is a WPF new feature. So let's discover its principal characteristics through this article.

Imagine that you host an image in your application in such way that its dimensions are bigger than the window. You can make use of a ScrollViewer to enable see the entire image without having the obligation to change the dimension of the given window. Try to host a big image within a given window. Say that the image height and width are both 1000 pixels.

<Window x:Class="myWpfApplication.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

    Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

      Loaded="Window_Loaded" >

            <Image Source="C:\myWpfApplication\myWpfApplication\image.BMP" Width="1000"Height="1000"></Image>

 

The result will be:

ScrollViewer1.gif
 
Figure 1

And even you expand the window. You couldn't get the entire image at the screen level. To prevent this problem you may use the ScrollViewer object as follow:

Replace the above XAML code by this one.

 

<Window x:Class="myWpfApplication.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

    Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

      Loaded="Window_Loaded" >

    <Grid>

    <ScrollViewer VerticalScrollBarVisibility="Visible"

                   HorizontalScrollBarVisibility="Visible">

        <Image Source="C:\myWpfApplication\myWpfApplication\image.BMP" Width="1000"Height="1000"></Image>

    </ScrollViewer></Grid>

</Window>

 

And the result will be

ScrollViewer2.gif
 
Figure  2

Then it is possible to scroll the image.

READ MORE

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;

        }

READ MORE

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

Introduction


Figure 1: 
SpiltView Navigation Framework

The very idea of SpiltView originates from the Navigation Framework inside a XAML application. The navigation framework was introduced with Silverlight. The major components of the Navigation Framework were:

  1. Frame
  2. Page

The Frame here is much like the browser that was used to contain a page that can be navigated back and forth. Here, the frontward stack and the backward stack.

They supported a series of methods, namely:

  1. GoBack()
  2. GoForward()
  3. CanGoBack()
  4. CanGoForward()

But often it's only about the navigation that the developers are concerned about. This is why you have SplitView. SplitView helps us to navigate by “type” and not the URI that we used to do in Silverlight. Also, we don't need to care about the physical location of the file as well. 

The Page 

The page has the following two methods:

  1. OnNavigatedTo(Param)
  2. OnNavigatedFrom()

These two overridden methods help to navigate and hence help us to interact with the page.

Although there are a few more things worth noticing in Page.NavigationCacheMode that are primarily concerned with whether the page is supposed to be created again or the same instance of the page will be rendered.

Jumping with SpitView

SplitView is there for navigation. That means this gives a smoother way to navigate with menus and making the UI smoother and more fluid. 

Where to use a SpiltView



Figure 2: 
SpiltView Usage

Universally this is also know as the “Hamburger Menu” because it has two pieces of bread forming a nice Big Boy burger. But yes, that’s the split view. It’s a menu that takes care of a tons of problems a developer has while transiting from one page to another or simply just navigating from one part of the app to another. 

Behaviors of a SplitView



Figure 3: 
Behaviors of a SplitView

A SplitView when it is tapped pops out a menu and shows various options. Although it's not a requirement to have the Split View respond to a tap request.

Where to get the SplitView from



Figure 4: 
Font Selection

The new Segoe Font will have the SplitView. All these are vectors and are oriented to the Windows 10 Style.

Application of the SplitView

A SplitView namely has the following 2 things:

  • SplitView.Pane
  • SplitView.Content

Details

Let's talk in details about SplitView.Pane.



Figure 5: SplitView Pane

A Pane is where the developer puts in all the buttons that are either on the left or the right of the application. The Pane will also takes the kinds of buttons that will be available for tapping in the application.

The SplitView.Content



Figure 6: 
SplitView Content

The most important property is the Content property. The Content Property sits over the frame and gives a navigation affordance. The Content also gives us a lot of grip with the overlay on the UI. 

The SplitView.PaneDisplayMode

Depending on whether the SplitView is open or closed we have the PaneDisplayMode as its property.



Figure 7: PaneDisplayMode Properties

The Inline, when set to true, will provide a jolting experience to the user since the content will shift the SplitView opened up. In case of the overlay although the content will not shift, it will simply have the splitview menu coming out as a flyer over the content. The CompactInline will have the capabilities of shifting the content to a large extent if the SplitView is set to true or just have a sleek thin outline when set to false. The Compact overlay will have the same properties like the overlay only difference is in both of the cases of a Compact Overlay there will be a slight shift of content.

READ MORE
...