Archives

Archives / 2014

Jun 6

admin

wpf

WPF TextBox Multiline

  • Created: 6/6/2014
  • admin

Making a Textbox multiline in WPF is pretty simple. You just need to set the AcceptsReturn property to true from the Textbox element and the TextWrapping property to Wrap. This will give you the wanted effect.

Below you can find a sample in XAML:


    
        
    

Jun 3

admin

wpf

WPF TextBox

  • Created: 6/3/2014
  • admin

The textbox is one the most popular controls in WPF. It allows user to input data or text into your application. The information they put in here is basically plain text that you can later manipulate using code. Below you can find a simple example using XAML code:


    
        
    


For changing the text inside the textbox, you can use the Text property and type the label you want to show. In the sample below, we're pre-filling the text with the welcome word:


    
        
    


Numeric textbox

If need to make a textbox just numeric, we need to add some simple code in the application that will validate the characters on the textbox and just let numbers to go through. Below you can check the XAML code:


    
        
    



This is the C# code:

namespace WpfApplication12
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }
    }
}


In the code above, we're validating that text contains numbers using regular expressions. If the text contains only numbers, the IsMatch method returns true allowing then the event to be handled. If not, the event is cancelled and nothing is changed on the textbox.

May 27

admin

wpf

WPF ToggleButton

  • Created: 5/27/2014
  • admin

The ToogleButton in WPF allows you to hold the actual state when it's clicked. It works like the checkbox control but it renders in a button. When the button is toggle for the first time the IsChecked property has a true value, when clicked again, it has a value of false.

The toggle button also fires a Checked event when the IsChecked property changes. It also has a property called IsThreeState that when enabled, changes the cycle of values that IsChecked can have to true, false and null as the third state.

Below you can check a sample in XAML code:


    
        
                      

   

On the first click you'll get the following screen:

On the second click you'll get the following screen:

And on the third click you'll get the following screen:

May 24

admin

wpf

WPF TextBlock Multiline

  • Created: 5/24/2014
  • admin

The WPF TextBlock allows to add labels to a form in its simplest form. We can say that the Label control is more advanced than the TextBlock one, but the TextBlock will fit most of the common scenarios. Below you can find a simple example of the TextBlock in XAML:


    
        Hello world!
    


In the previous screen shot we can see a simple label been drawn in the window. You can also check that there's no margin at the top or left but we can easily change this using the margin property.


    
        Hello world!
    


WPF TextBlock and Multilines

One of the problems that we usually confront with the TextBlock is how to deal with multiple lines, like what happens when a line or label is too big that is doesn't fit the window. For this, we can use several approaches to handle the big string. Below you can check an example with all possible variations:


    
        This is a very very very very very very long line of text
        This is a very very very very very very long line of text
        This is a very very very very very very long line of text
    

In the previous sample, we're dealing with the multiple lines in various ways.

  • The first one, we're just adding a LineBreak control in the middle of the string forcing it to insert a carriage return and breaking the line. This is perfect for when you want to explicitly add the line break. This is the same as the
    tag in HTML.
  • In the second TextBlock, we're just add an ellipsis at the end of the string. using the TextTrimming property. This is great for when you have long text and just don't know where to break the line. WPF will automatically add the ellipsis at the end of the window so you don't have to do these calculations yourself.
  • The third TextBlock is cutting the line using the Wrap value of the TextWrapping property. It'll simply wrap the text to fit the window as needed. Also, the calculation for wrapping is done automatically for you and it changes when the window resizes by any action from the user.
May 16

admin

wpf

WPF LinkLabel

  • Created: 5/16/2014
  • admin

WPF doesn't include a control that displays a hyperlink like LinkLabel that was included in Windows Forms. But still, this kind of control is really important and can have a lot of uses around our applications.

What I have done below is simply combine multiple WPF controls to recreate a simple LinkLabel that you can actually click and browse to some address on the Internet. Below you can find the XAML markup:


    
        
            The link Text
        
    


And this is the C# code:

namespace WpfApplication9
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(LinkLabel.NavigateUri.ToString());
        }
    }
}

In the code above I'm just creating a TextBlock and adding the Hyperlink inside of it. Then defining the NavigateUri property with some url and then adding the text. In the C# code, we're just handling the click and opening a process and passing the url as a parameter. This will open the default browser with the link.

May 14

admin

wpf

WPF ListBox ItemTemplate

  • Created: 5/14/2014
  • admin

ItemTemplates in WPF ListBoxes allows you to present information to users in a way that makes more sense for them without having to do a lot of programming. For example, let's say you have information that you'd like to present about some web search results. The objects holding the information look like this:

List results = new List();
            results.Add(new SearchResult() { SiteTitle = "SkyXoft", SiteDescription = "Provide useful software to customers", SiteUrl = "http://www.skyxoft.com" });
            results.Add(new SearchResult() { SiteTitle = "LicenseSpot", SiteDescription = ".NET licenisng in the cloud", SiteUrl = "http://www.licensespot.com" });
            results.Add(new SearchResult() { SiteTitle = "Expiration Reminder", SiteDescription = "Keep your expirations in one place", SiteUrl = "http://www.expirationreminder.net" });

Displaying this information in a listbox without any formatting will look like the image below:

As you can see, it just even have the object names. If we want, we could add a ToString method to the object so we can get some more meaningful information but this is not what we want to achieve. We want to give it some styling using WPF controls.

ListBox and the ItemTemplate

For giving it some styling, we can use the ItemTemplate element of the ListBox and inside it declare a DataTemplate that will hold the information for displaying the results. In this case, we want to paint the items in the list like the results from web search. For this, we're using the following XAML markup:


    
        
            
                
                    
                        
                        
                        
                    
                
            
        
    


And also the following C# code:

namespace WpfApplication9
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List results = new List();
            results.Add(new SearchResult() { SiteTitle = "SkyXoft", SiteDescription = "Provide useful software to customers", SiteUrl = "http://www.skyxoft.com" });
            results.Add(new SearchResult() { SiteTitle = "LicenseSpot", SiteDescription = ".NET licenisng in the cloud", SiteUrl = "http://www.licensespot.com" });
            results.Add(new SearchResult() { SiteTitle = "Expiration Reminder", SiteDescription = "Keep your expirations in one place", SiteUrl = "http://www.expirationreminder.net" });

            SearchResultsListBox.ItemsSource = results;
        }
    }
    public class SearchResult
    {
        public string SiteTitle { get; set; }
        public string SiteDescription { get; set; }
        public string SiteUrl { get; set; }
    }
}

As you can see, now we have the results in a nicely formatted way. In the code, we're just declaring the ItemTemplate element and inside it we're adding a StackPanel and then adding TextBlock objects that will render information in the interface. We then just use some basic WPF properties to change the colors and fonts.

May 9

admin

wpf

WPF ListBox Binding

  • Created: 5/9/2014
  • admin

Binding a ListBox to a collection is simple. You just need to declare the Binding element in the XAML markup to make the connection to the list of objects. This will allow the ListBox to automatically populate itself with the items.

Below you can find the XAML markup example:


    
        
            
                
                    
                
            
        
    


An this is the C# code:

namespace WpfApplication8
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List colors = new List();
            colors.Add(new MyColor("Red"));
            colors.Add(new MyColor("Green"));
            colors.Add(new MyColor("Blue"));

            ListBoxTest.ItemsSource = colors;

        }

    }
    public class MyColor
    {
        public string Name { get; set; }

        public MyColor(string n)
        {
            this.Name = n;
        }
    }
   
}

In this sample we're binding the Name property of the MyColor class to the Text property of the TextBlock element. We're connecting both using the ItemsSource property of the ListBox object. This will automatically fill the ListBox

Binding to an ObservableCollection

Binding to an ObservableCollection will allow the ListBox to refresh itself anytime a change is made in any of the items on the List. This way, you don't need to tell the ListBox to look for the items again as the change will automatically trigger an event in the collection the the ListBox will catch and handle.

To do this, we just need to create the item that implements the INotifyPropertyChanged interface and handle the necessary events. Below, we've changed the MyColor class so it can support Observables:

public class MyColor : INotifyPropertyChanged
    {
       
        private string name;
       
        public String Name
        {
            get { return name; }
            set
            {
                if (name == value) return;
                name = value;
                RaisePropertyChanged("name");
            }
        }

        public MyColor(string n)
        {
             this.Name = n;
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propName)
        {
            PropertyChangedEventHandler eh = PropertyChanged;
            if (eh != null)
            {
                eh(this, new PropertyChangedEventArgs(propName));
            }
        }
    }

When building the list, we don't use now a simple List object, we implement it using the ObservableCollection object as shown below:

ObservableCollection colors = new ObservableCollection();
colors.Add(new MyColor("Red"));
colors.Add(new MyColor("Green"));
colors.Add(new MyColor("Blue"));

ListBoxTest.ItemsSource = colors;
May 7

admin

wpf

WPF ListBox

  • Created: 5/7/2014
  • admin

The ListBox control in WPF allows you to display a list of items to the user. The user can then select one item or multiple items as needed.

Below you can find an example with XAML markup:


    
        
            Red
            Green
            Blue
        
    


Getting selected items

To the get the selected item in the ListBox you can use the SelectedItem property to get a single item or the SelectedItems property to get multiple items.

Below you can find an example for getting selected items:


    
        
        
            
                
                    
                
            
        
    


namespace WpfApplication8
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List colors = new List();
            colors.Add(new MyColor("Red"));
            colors.Add(new MyColor("Green"));
            colors.Add(new MyColor("Blue"));

            ListBoxTest.ItemsSource = colors;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            foreach (MyColor item in ListBoxTest.SelectedItems)
            {
                MessageBox.Show(item.Name);
            }

        }


    }
    public class MyColor
    {
        public string Name { get; set; }

        public MyColor(string n)
        {
            this.Name = n;
        }
    }
   
}
May 3

admin

wpf

WPF StackPanel

  • Created: 5/3/2014
  • admin

The StackPanel is a layout control that allows you to organize controls one beside the other or one below the other. You can select the orientation by using the Orientation attribute on the element. Many other controls use the StackPanel internally to layout controls like the Menu, ComboBox or ListBox.

Below you can check a simple example:


    
        
            
            
            
            
            
        
    


Horizontal Stacking

If you want to stack the items inside the panel horizontally, you just have to set the Orientation attribute in the element to Horizontal like in the sample below:


    
        
            
            
            
            
            
        
    


Add padding to the StackPanel

If you want to add some padding to StackPanel, you can combine it with the Border control and then add the padding to the Border element as shown in the XAML markup below:


    
        
        
            
            
            
            
            
        
        
    


May 2

admin

wpf

WPF Timer

  • Created: 5/2/2014
  • admin

In windows forms we had class called Timer that allowed us to execute a certain piece of code in our application in a predefined schedule. In WPF we have better class called the DispatchTimer. Using this class we can schedule a event to trigger depending on a certain amount of time that we specify.

Below you can find a XAML mark up of an application that simulates a stop watch:


    
        
            
               
                
                
               
            
            
        
    


And this is the C# code:

namespace WpfApplication6
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        private DispatcherTimer timer;
        public MainWindow()
        {
            InitializeComponent();

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            TimerLabel.Content = DateTime.Now.ToLongTimeString();
        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            timer.Start();
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            timer.Stop();
        }
    }
}

In the code above, we're setting up a timer variable and creating an instance of it in the window constructor. We're then setting the inverval in which the timer should trigger to one second. The next line just sets up the event that will handle when the trigger actually fires. When the event executes, it basically sets the content of the TimerLabel to the actual time.

Timer Tick

The timer tick is the property where we can configure the event that will be triggered when the timer interval lapses. In our code above, is executing the method timer_Tick

Timer and the UI

The interesting thing about DispatchTimer is that it executes on the Dispatcher queue which runs on separate thread than the one our application runs. This means, that when the timer runs and triggers the Tick event, I can actually draw on the screen with any lags, giving us the opportunity to do any kind of animation and screen updating as needed.

Apr 30

admin

wpf

WPF Dockpanel

  • Created: 4/30/2014
  • admin

The dock panel allows you to dock elements on the window in any direction, either top, bottom, left or right. This is useful when you want to divide the window or screen into specific areas with different functionality. It's also useful because the last element will take the whole remaining space in the center, unless this is disabled in the markup code.

The dock elements in the windows, you need to use the DockPanel.Dock element in the controls that you want to anchor. These controls must be declared inside the Dock element to take advantage of this feature. The DockPanel.Dock attribute takes the value of the position you want the control anchored. Below you can find a XAML markup example:


    
        
            
            
            
            
            
        

    


As you can see, we don't need to indicate the dock position of the last element because it'll automatically centers and takes the rest of the space. Another thing to keep in mind is that the controls only take the space that they need. The rest of the space is taken by the center.

You can also observe that some of the controls take more space than the others. For example, the Top button takes the whole width and also the Bottom one. But the Left and Right they just take the height between the Top and the Bottom. This is because of the order in which the controls were added in the dock panel.

Disabling the last child fill

As we mentioned earlier, the last control takes the whole space left in the center. If you want to disable this, just set the LastChildFill property to false and the control won't take the whole space. Below you can see an example:


    
        
            
            
            
            
            
        

    

Apr 27

admin

wpf

WPF TabControl Styling

  • Created: 4/27/2014
  • admin

Adding style to the WPF TabControl isn't to difficult. The default style for tabs are pretty generic so you might want to add some styling so the interface looks nice. You can change the borders for the tabs, the background color, the margins and where you want the text for header to go.

Below you can find sample in XAML code


    
        
            

                         

As you can see, we're simply adding a Style element to the tab control setting it's target to the TabItem. We then do a ControlTemplate and set the necessary style elements we want it to have. We're also setting some Triggers that will happen for example when the user clicks on the tab. In the this case, we're changing the BackGround property

Apr 25

admin

wpf

WPF TabControl

  • Created: 4/25/2014
  • admin

The WPF tabcontrol allows you to divide information to the user in a single screen. Each tab you configure have different set of controls and content that it's used to present or gather feedback from the application user.

Below you can a simple example in XAML on how to use the tab control with three tabs:


    
        
            
                
            
            
            
            
            
        

    

In this sample, the tab control has three tabs defined. The tabs are declared using the TabItem mark up in XAML. This element has property called Header that we can use to name the tabs in the user interface. Inside the TabItem element we inject any content that we need. In this example, I'm creating a Label in the first tab, but you can add as many other elements as you need.

Changing the headers

Because the headers can also have content, you can customize it with other element or control that you wish. In the sample below, we'll add some circles before the labels to give it some colors:


    
        
            
                
                    
                        
                        
                    
                
                
            
            
                
                    
                        
                        
                    
                
            
            
                
                    
                        
                        
                    
                
            
        

    


There's a lot mark up in this example, but we're just basically customizing the Header property by adding a TabItem.Header element and then adding a StackPanel inside it. We need the StackPanel to be able to add multiple elements inside the property. Then we add an Ellipse which will draw a circle next to our header text. The header text is defined by the TextBlock element. We can also style the TextBlock however we want (bold, italics, color, etc.)

TabControl Events

Getting the selected can be done using the SelectedItem property and casting it into a TabItem. You can see an example below:

var tabItem =TabControl.SelectItem as TabItem;
var header = tabItem.Header;
Apr 24

admin

wpf

WPF Margin

  • Created: 4/24/2014
  • admin

The margin property in WPF allows you set spacing between elements in a window. You can assign the margins for the Top, Right, Bottom and Left.

Every control that derives from FrameworkElement has this property.

A simple mark up XAML code with margins is:


    
        

    

It'll render something like this:

Margin in code

The margin property is of type Thickness so you should be able to set margins in code using the following snippet:

buttonTest.Margin = new Thickness(0, 120, 9, 213);

Apr 24

admin

wpf

WPF ListView Sorting

  • Created: 4/24/2014
  • admin

If you need to apply sorting to a ListView, this can be done easily. We just need to handle the GridViewColumnHeader.Click on the ListView. Below you can find the XAML code for doing this:


    
        
            
                
                    
                    
                    
                
            
        
    

And the C# code to handle the click event:

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        GridViewColumnHeader _lastHeaderClicked = null;
        ListSortDirection _lastDirection = ListSortDirection.Ascending;

        public MainWindow()
        {
            InitializeComponent();

            ObservableCollection businesses = new ObservableCollection();
            businesses.Add(new Business("Microsoft", "http://www.microsoft.com", "123-421-1231"));
            businesses.Add(new Business("SkyXoft", "http://www.skyxoft.com", "123-321-1231"));
            businesses.Add(new Business("LicenseSpot", "http://www.licensespot.com", "123-312-3212"));

            BusinessListView.ItemsSource = businesses;



        }
        private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
            ListSortDirection direction;

            if (headerClicked != null)
            {
                if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (headerClicked != _lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (_lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    string header = headerClicked.Column.Header as string;
                    Sort(header, direction);

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }
        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView = CollectionViewSource.GetDefaultView(BusinessListView.ItemsSource);

            dataView.SortDescriptions.Clear();
            SortDescription sd = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sd);
            dataView.Refresh();
        }

    }
    public class Business
    {
        public string Company { get; set; }
        public string Url { get; set; }
        public string Phone { get; set; }
       
        public Business(string company, string url, string phone)
        {
            this.Company = company;
            this.Url = url;
            this.Phone = phone;
           
        }
    }
}

In the code above we are creating three records in the List and binding it to the ListView. This is the simple and straightforward part.

The difference here is the click event. First we determine what header was clicked and we save that information on the headerClicked variable. Then we checked with a class variable what was the last header clicked. If it is different from the one we just clicked, the the grid is just sorted in ascending mode by default. If it's the same header, then we determine what was the last direction it was clicked and select whether to sort ascending or descending.

At the end we have the Sort method. This will actually get a default view from the ListView ItemsSource. This view has the functionality to sort the rows. We just need create a SortDescription object with the parameters about the header clicked and the direction and call the Refresh method. This will do the trick.

Apr 24

admin

wpf

WPF ListView Binding

  • Created: 4/24/2014
  • admin

Binding in the ListView will allow you to get information from a database or a list and bind that information to controls. This way, you don't need to manually insert the data into the controls, the ListView will do this automatically.

Below you can an example in XAML on how to use binding:


    
        
            
                
                    
                    
                    
                
            
        
    

What we have here is a ListView showing information as a gird. Each column in the grid is bind to a property and this is done using the DisplayMemberBinding attribute. This is indicating to which property in the dataset or object the column maps to.

Binding multiple columns

Binding to multiple columns in the ListView is also pretty straightforward. In the previous XAML sample we're actually binding to more than one column. By adding the C# code below, we can populate this ListView:

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List businesses = new List();
            businesses.Add(new Business("Microsoft", "http://www.microsoft.com", "123-421-1231"));
            businesses.Add(new Business("SkyXoft", "http://www.skyxoft.com","123-321-1231"));
            businesses.Add(new Business("LicenseSpot", "http://www.licensespot.com", "123-312-3212"));

            BusinessListView.ItemsSource = businesses;

           

        }
    }
    public class Business
    {
        public string Company { get; set; }
        public string Url { get; set; }
        public string Phone { get; set; }
       
        public Business(string company, string url, string phone)
        {
            this.Company = company;
            this.Url = url;
            this.Phone = phone;
           
        }
    }
}

What we're doing is create a List of Business objects and filling with information. Each Business object has a Company, Url and Phone property that maps to the bindings defined in the XAML markup. When we assign it to the ItemsSource property in the ListView, it'll be automatically filled:

Binding and SelectedItems

For getting the selected items in the ListView when using binding, we simply need to use the SelectedItems property of the ListView and loop through it. The following code shows an example:

foreach (Business business in BusinessListView.SelectedItems)
{
     MessageBox.Show(business.Company);
}

Notice that when we do the for each, the SelectedItems actually holds the objects binded to the ListView, so a cast is automatically done and we can interact with the object right away.

Binding and ObservableCollection

Binding to an ObjservableCollection is also pretty straightforward. In the sample below we're changing the value of the Company propety for the first item in the List. When we run the project, you can see that the value is changed on the ListView and we didn't have to rebind it or do any more coding:

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ObservableCollection businesses = new ObservableCollection();
            businesses.Add(new Business("Microsoft", "http://www.microsoft.com", "123-421-1231"));
            businesses.Add(new Business("SkyXoft", "http://www.skyxoft.com","123-321-1231"));
            businesses.Add(new Business("LicenseSpot", "http://www.licensespot.com", "123-312-3212"));

            BusinessListView.ItemsSource = businesses;

            businesses[0].Company = "Microsoft Corp";
           
        }
    }
    public class Business
    {
        public string Company { get; set; }
        public string Url { get; set; }
        public string Phone { get; set; }
       
        public Business(string company, string url, string phone)
        {
            this.Company = company;
            this.Url = url;
            this.Phone = phone;
           
        }
    }
}

Apr 24

admin

wpf

WPF ListView Grouping

  • Created: 4/24/2014
  • admin

Another feature that we have with the ListView is grouping. This will allow you to group rows depending on a specific field. This feature can be customized as needed and give your application extreme usefulness visualizing information.

Below you can see a sample with the XAML and the C# code:


    
        
            
            
        
        
            
                
                    
                    
                    
                
                
            
            
                
                    
                        
                            
                        
                    
                
            
        
    

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List businesses = new List();
            businesses.Add(new Business("Microsoft", "http://www.microsoft.com", "123-421-1231","Enterprise"));
            businesses.Add(new Business("SkyXoft", "http://www.skyxoft.com","123-321-1231","SMB"));
            businesses.Add(new Business("LicenseSpot", "http://www.licensespot.com", "123-312-3212","SMB"));

            BusinessListView.ItemsSource = businesses;

            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(BusinessListView.ItemsSource);
            PropertyGroupDescription groupDescription = new PropertyGroupDescription("Size");
            view.GroupDescriptions.Add(groupDescription);

        }
    }
    public class Business
    {
        public string Company { get; set; }
        public string Url { get; set; }
        public string Phone { get; set; }
        public string Size { get; set; }
        public Business(string company, string url, string phone, string size)
        {
            this.Company = company;
            this.Url = url;
            this.Phone = phone;
            this.Size = size;
        }
    }
}

In this sample we've taken the list of businesses and grouping them based on the size of the company. In the XAML we've just added a GroupStyle to the list view in which a template is defined. This template includes a TextBlock that holds the information for the grouping. It has a different style, a bold, to note the difference. The text property is bound to the Name field but it has nothing to do with the Business object. This Name property holds the name of the group as assigned by WPF.

In the C# code we're just adding the objects to a List but we're also using the CollectionView object which has the ability to group items. We do so by creating a PropertyGroupDescription object and adding it as a GroupDescription in the CollectionView. This tells WPF to group the items using the specified property.

Add an expander to the group header

In the previous example, we showed how to group the rows in the ListView. But one common request from end users is to have the ability to expand and collapse the group headers so they can filter the information they see in the screen. In WPF in can't do this by default but we can some templates to do it.

Below you can find the XAML code:


    
        
            
            
        
        
            
                
                    
                    
                    
                
                
            
            
                
                    

     

There's no need to modify the C# code, we can use the same one. In the XAML code we're just adding the Expander property and setting it to true to show it the ListView. As you can see in the screenshot, we can now group by the size of the company. We also added the number of items inside the group using the ItemCount property which is also available in the group.

With this, you can quickly style the group to your own requirements and build grid interfaces that really provides added value to your users.

Apr 24

admin

wpf

WPF ListView with GridView

  • Created: 4/24/2014
  • admin

In this article we'll talk about using the ListView but with one of it's most useful feature: the GridView. With this functionality we're able to present data to users in the form of tables and rows, just like a data grid would do in the old Windows Forms space.

Below you can find a pretty simple example of a list view with three columns:


    
        
            
                
                    
                    
                    
                
            
        
    

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List businesses = new List();
            businesses.Add(new Business("Microsoft", "http://www.microsoft.com", "123-421-1231"));
            businesses.Add(new Business("SkyXoft", "http://www.skyxoft.com","123-321-1231"));
            businesses.Add(new Business("LicenseSpot", "http://www.licensespot.com", "123-312-3212"));

            BusinessListView.ItemsSource = businesses;
        }
    }
    public class Business
    {
        public string Company { get; set; }
        public string Url { get; set; }
        public string Phone { get; set; }

        public Business(string company, string url, string phone)
        {
            this.Company = company;
            this.Url = url;
            this.Phone = phone;
        }
    }
}

In this sample, we have a ListView with three simple columns. We're just changing the default View for the list view to be GridView (this is the only one available but you can create your own). We then just define the columns using the XAML markup as shown above. In each column we're defining the Header that's shown at the top of the grid, the width and the DisplayMemberBinding that binds the value of the column to the actual object we're using in the C# code.

Using templates as cell content

We can add our own controls to grid view columns using the CellTemplate property in WPF. This give us the option to render the content of the columns in any way that we need instead of just displaying strings as the DisplayMemberBinding property does.

In the sample below, we'll be changing the url column to display what an actual link looks like by using the TextBlock element:


    
        
            
            
        
        
            
                
                    
                    
                        
                            
                                
                            
                        
                    
                    
                
            
        
    

As you can see, this very simple. In the middle columns we just specified that we wanted a CellTemplate to be used, define what we wanted as a template (in this case a TextBlock) and just let the control know how to bind to the property. You can use this same approach to basically use any other element as a CheckBox for example as shown in the ListView checkbox sample.

Apr 12

admin

wpf

WPF ListView with CheckBox

  • Created: 4/12/2014
  • admin

In this article we'll talk about how to render check boxes inside a ListView. You can use this feature for example, for presenting a list of options to ends users and allowing them to select one option or multiple options. The way you do this is by using DataTemplates inside the ListView and then do some basic data binding to show the controls. In the sample below I've also added functionality to hide the headers for the ListView. The final product we'll essentially look like this:

Adding check boxes to the ListView

To add the check box to each list view item, we need to change the XAML generated for the list and include and add a GridView and will contain two columns: one for the check box and one for the label. Below you can see the XAML code for this, specifically inside the tag:


     
          
               

                 

Hiding the column headers For hiding the headers we just need to style the GridView header and set the Visiblity property to Collapsed as shown in the XAML below:



Binding the check boxes to the ListView

For the binding, I created a class that has two properties: Text and IsChecked. These properties hold the values to the two columns our ListView has. Text will have the actual label to show in the second column and IsChecked determines if the checkbox is checked. It actually represents the object for each row in the list view. It's also implementing the INotifyPropertyChanged that will allow the ListView to update itself when a value in the object changes. You can see the code below:

public class CheckBoxListViewItem : INotifyPropertyChanged { private bool isChecked; private string text; public bool IsChecked { get { return isChecked; } set { if (isChecked == value) return; isChecked = value; RaisePropertyChanged("IsChecked"); } } public String Text { get { return text; } set { if (text == value) return; text = value; RaisePropertyChanged("Text"); } } public CheckBoxListViewItem(string t, bool c) { this.Text = t; this.IsChecked = c; } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propName) { PropertyChangedEventHandler eh = PropertyChanged; if (eh != null) { eh(this, new PropertyChangedEventArgs(propName)); } } }

Now we'll just create some test objects when the Window is created for testing:

ObservableCollection items = new ObservableCollection();
items.Add(new CheckBoxListViewItem("Red",false));
items.Add(new CheckBoxListViewItem("Green", true));
items.Add(new CheckBoxListViewItem("Blue", false));

myListView.ItemsSource = items;

This gives you the result below:

Check all button for the ListView

Adding a Check All button is also pretty simple. On click event for the button we just need to loop through the check boxes change the IsChecked property to true. This will automatically notify the ListView and update itself. Below you can see the code:

private void CheckAllButton_Click(object sender, RoutedEventArgs e)
{
    
     foreach (CheckBoxListViewItem o in myListView.ItemsSource)
     {
          o.IsChecked = true;
         
     }

 
}

Apr 9

admin

wpf

WPF ListView

  • Created: 4/9/2014
  • admin

The ListView is a control that allows you present data to the user using different layouts. The most common one is showing a table with columns with the information. The ListView inherits from ListBox and in WPF provides a number of features that give it a great deal of extensibility being one of them to present information in different formats. Information or data in the ListView is contained within objects. The most basic one is the ListViewItem object that simply represents and item with a single column ListView.

ListView example

Here’s the code of a ListView sample that contains three basic items in the ListViewItem object:


            
            
        

As you can see, we’re able to create it using simple XAML markup giving us the advantage to shape the information as we wanted using WPF functionality. In the code below we have the same list but with the items in bold and italics:


            
            
            
        

 

Apr 8

admin

wpf

WPF MessageBox

  • Created: 4/8/2014
  • admin

A message box is a small dialog window display on the screen for the users. It can have an icon, a message and a button (or a set of buttons) for the user to provide feedback. The MessageBox is contained within the System.Windows.Forms namespace and is part of the Windows Forms library and objects since the launch of the .NET Framework. This class contains a static method called Show that draws the dialog in the screen. It also returns an enumeration with the values No, Yes, Cancel, OK and None.

MessageBox Example

Below you can find the code on how to show a simple message box with an OK button. After pressing the OK button, the dialog will close:

DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" );

The result variable will contain which button the user selected. In this case, result will always be OK.

MessageBox with Title

In this example, we’re creating a message box with a message an OK button but we’re also setting a caption that shows on the top bar:

DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App" );

MessageBox Yes/No

When we need to gather feedback from the user about a question, we can create a message box with a message and two buttons, one for YES and one for NO using the code below:

DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App",MessageBoxButtons.YesNo);

Handling the MessageBox result

After we’ve capture the results, we need to take an action about it. This is as simple as testing the value in the result variable as shown below:

DialogResult result = System.Windows.Forms.MessageBox .Show("Hello World" ,"My App",MessageBoxButtons.YesNo);

if (result == System.Windows.Forms. DialogResult.Yes)
{
}
else
{
}

MessageBox style

As you may have already noticed, the MessageBox class uses the User32 libraries directly preventing it to provide a true WPF experience. In this case, if you still want to produce this kind of experience you’ll need to create your own windows screen or use a third party library. In our tests, we recommend you use the WPF Toolkit on CodePlex that already has a Message Box that you can style as needed.

MessageBox Icon

You can also set an icon to show on the left part on the message box. This is used to give direct information to the user about what’s been said in the box. For example, if it’s a question, information or an error has occurred. For this, there’s an enumeration that has all the possible values as follows: None Hand Question Exclamation Asterisk Stop Error Warning Information Below is the code of message box with an error icon:

DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App",MessageBoxButtons.YesNo, MessageBoxIcon.Error);

 

Mar 22

admin

.NET Licensing System

  • Created: 3/22/2014
  • admin

If you're in the market for a licensing system for .net, here are some of the components you should consider as you evaluate the different products out there in the market.

Licensing System

This is the core part every product should have. It actually generates the licenses using a predefined algorithm to help protect the actual software program. The most popular and secure one is using digital certificates, essentially, private/public key system. With this, a private key is used to sign a document that contains information about the license. Then the public key is used by the software being protected to validate that the document hasn’t been altered and that is valid.

The licensing system should provide you with a way to keep track of these keys and save them somewhere safe. An online licensing system can do this by default by saving the key pairs on the online database where it can’t reached by malicious users.

License Management

This feature will allow you to manage the license files and generated serial numbers. For customer support reasons, you’ll need to go back to these licenses and verify the information in it. For example, you might save what version of a product your customer is using (Lite, Professional or Enterprise). This information is saved in the license.

Also you might need to modify the information for example when a customer upgrades or you want to give them a special license. You need a way to quickly find these licenses.

Customer Management

Similar to license management, customer management will allow you to find customers by their name or email, get their information and check what licenses they currently have of your product.

Again, for support reasons, this is the fastest way to find license information for a customer. This feature will also serve as the actual customer database for your products so you can also tap on it for resources and future notifications you want to send to your clients.

Notification System

The notification system will automatically deliver licenses to your end users after they buy or activate the license. This way, you don’t need to code this on your side of things.

The notification system will also make sure emails are delivered. At the same time, the licensing system should provide you with the tools to change the email templates so you can include your own wording.

Payment Provider Integration

If you’re licensing a software product it’s because your intention is to sell it to other people. Providing integration with major payment providers will allow you to automatically create the license or serial number on the fly when the customer pays. Then using the notification system, the license is also delivered to the customer instantly.

The integration with the payment provider should be done with the minimal amount of code or maybe none. For example, in LicenseSpot, you can configure payment providers with just a few clicks and using minimal information. This allows licenses to be created online.

Templating System

The templating system serves as way to automatically create licenses based on predefined templates. These templates contain information about the license.

For example, you can have a template for trials and a template for production licenses. The trial specifies how much time the license is valid. A template specifies the limits the application has. Furthermore, the production template can be divided into one for the lite version and one for the professional version. Then by just selecting the right template, the license is automatically created based on these values.

Hosting

When you’re doing online activations, also consider the hosting the license provider has. You don’t want to host this kind of systems by yourself as you can easily loose customers when they’re unable to activate because your server is unavailable. Ask for how many servers and what’s the SLA they provide on the service.

In LicenseSpot, this something we take really serious as we host the product on a server farm on Windows Azure providing high availability.

In conclusion, keep an eye on all these items when you’re looking to buy a licensing system for .net (either for C# or VB.NET) so you can get the best bang for your money.

Mar 16

admin

Licensing .NET Applications

  • Created: 3/16/2014
  • admin

When you’re done writing your application and everything is ready for launch, the final step is licensing your application. Licensing is the process of avoiding casual piracy in your software product and there are multiple ways to this in .NET.

Types of Piracy

The first thing you should know is that applying licensing to your app doesn’t mean that it won’t be pirated. There are two kinds of piracy in the software market: casual piracy and actual piracy. The actual piracy is when someone or a company is decided on using an unlicensed product and will do whatever is necessary to get it. This includes getting fake serial numbers or cracking the application. You can’t stop this kind of piracy from happening. There’s nothing you can do in your application that wouldn’t allow a person to deobfuscate your code and inject their own to prevent licensing from working.

But casual piracy is different. You can find this one generally inside companies when they have purchased a license of a product for five users. Then all of sudden they need an extra one a, sixth user, and they just proceed to install it and use it. This is the one we want to prevent. Their intent isn’t to pirate or crack the application, they’re just doing it because they can or it’s just temporary.

Protection mechanism

The most well-known way of protecting .NET software is using the public/private key mechanism or digital signatures. With this system, a private key is used to sign a document and a public key is used to verify that the document was signed using the private key. After the document has been originally signed, it cannot be altered. Changing its contents, will break validation using the public key.

Encrypting the data isn’t useful because you’ll need the encryption key to be present in the program to decrypt the document. The pirate could simply take a look at your IL code using any disassembler, take the key and unencrypt the file, change it and encrypt it again.

For your product, you can for example create an XML file that contains information about the user, company, serial number, what features the license allows and trial information. Then you can sign the XML using a private key and distribute this file as the license. Nobody will be able to modify the file because they don’t have the private key. This one is stored (safely somewhere) in your computer and never distributed. For creating the license file and delivering it to the user you can use online activation. This is the method used by Windows and Office and are the ones users are more familiar with so you don’t need to do any training or let them go through a manual process for copy the license file.

Additional Protection

The only downside to using digital signatures is that a hacker can create its own private/public key pair and inject this into your program. You can prevent this from happening by using signing your code using the strong name utility (SN.exe) that comes with Visual Studio and tell it to sign your assembly. By doing this, the runtime will always check the assembly hasn’t been altered before loading the application.

Obfuscation can also help, making it difficult for the person trying to crack your product. The person won’t be able to easily understand the code and adds an extra layer of complexity to the hacking process. But we need to keep mind, that users decided to crack the program, will find ways to deobfuscate it.

Also, you can spread the method for validating your app all over the place. This will make it more difficult for the cracker to inject its code in the product.

Conclusion

In conclusion, follow all these practices and you’ll get a better chance at protecting your application. Using obfuscation, strong name signing and digital signatures for the license file are effective at protecting your property.

Sample Code

Below you can find demo code for signing a document using a private key:

      public XmlDocument SignXmlDocument(string licenseContent, string privateKey)  

{

            RSA key = RSA.Create();

           key.FromXmlString(privateKey);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(licenseContent);

            SignedXml sxml = new SignedXml(doc);

            sxml.SigningKey = key;

            sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;

            // Add reference to XML data

            Reference r = new Reference("");

            r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

            sxml.AddReference(r);

            // Build signature

            sxml.ComputeSignature();

            // Attach signature to XML Document

            XmlElement sig = sxml.GetXml();

            doc.DocumentElement.AppendChild(sig);

            return doc;

        }

This code snippet will validate the document using a public key:

public bool VerifyXmlDocument(string publicKey, string licenseContent)

        {

            

            RSA key = RSA.Create();

            key.FromXmlString(publicKey);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(licenseContent);

            SignedXml sxml = new SignedXml(doc);

            try

            {

                // Find signature node

                XmlNode sig = doc.GetElementsByTagName("Signature")[0];

                sxml.LoadXml((XmlElement)sig);

            }

            catch (Exception ex)

            {

                // Not signed!

                return false;

            }

            return sxml.CheckSignature(key);

        }

Mar 16

admin

FastSpring integration

  • Created: 3/16/2014
  • admin

Licenses and serial numbers can now be automatically created when a new order is created in FastSpring. This integration can be done without having to throw a single line of code. Everything is done through the LicenseSpot interface and the FastSpring administration site.

Combined with our email triggers feature, allows a complete delivery of the license to the customer from order, serial number generation and delivery through email.

You can check how to integrate it in this video.

Mar 16

admin

Network floating licensing limit

  • Created: 3/16/2014
  • admin

Now you can add network floating licenses to your .net applications using the network limit in LicenseSpot. With this, you can limit how many instances of your application can run concurrently on your end user or customer environment.

This feature is completly integrated with our online server so you don't have to do any server installation on the customer site. Your software simply connects to our servers to check the actual license usage. If the limits is exceeded, you just cancel the loading of the application.

You can get more information about the network limit on the documentation.

Mar 16

admin

Subscription support for desktop apps

  • Created: 3/16/2014
  • admin

You're now able to easily add subscription support to any kind of .NET application, including desktop software. You can add this using the subscription limit feature in LicenseSpot.

In conjunction with the Time limit, users are also able to restrict the period in which the subscription is valid. For example like 30 or 15 days. Both of these limits can work together pretty easily.

Also we've added Stripe support which allows the subscription license to be automatically deactivated if the plan is cancelled by Stripe because of problems with payment. You can also configure custom emails from LicenseSpot to be sent to the customer using the email triggers feature depending on events ocurring in Stripe like charge failure or cancellation.