Archives
WPF ToggleButton
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:
WPF TextBlock Multiline
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.
WPF LinkLabel
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.
WPF ListBox ItemTemplate
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:
Listresults = 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(); Listresults = 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.
WPF ListBox Binding
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(); Listcolors = 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:
ObservableCollectioncolors = new ObservableCollection (); colors.Add(new MyColor("Red")); colors.Add(new MyColor("Green")); colors.Add(new MyColor("Blue")); ListBoxTest.ItemsSource = colors;
WPF ListBox
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(); Listcolors = 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; } } }
WPF StackPanel
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:
WPF Timer
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.