Tag Archives: Visual C# 2010

Windows Presentation Foundation Using Visual C# 2010: Introducing Binding

As you write applications, you often need to update the value of one element with information from another element. Often, you need to display information coming from a collection of objects in a list, or combo box. Or, perhaps you need to work with data coming from a data source, such as a database. In all these cases, the simplest solution is to bind data from a data source to a target element; in other words, you need binding capabilities.

Data binding makes it simple for applications to display and interact with data. You use a connection, or binding, between the data source and the target; this binding object allows data to flow between the source and the target objects. Once you have created a binding, and you change data in the data source, the changes appear in the target. If you have enabled two-way data binding, you can also make changes in the target and have those changes appear back in the original data source.

When might you use binding? You might use binding to:

  • Display the number of characters in a text box, in a TextBlock control.
  • Display the value of a Slider control in a TextBlock control.
  • Display a list of customers in a ListBox control.
  • Display a customer’s photo in an Image control.
  • Display and edit a customer’s name in a TextBox control.

Obviously, there are infinite reasons to use binding, and XAML makes it easy.

Connecting Sources and Targets

Every time you use binding, you must supply a source for the data, and a target (normally, a dependency property of some user interface element). Figure 1 demonstrates the basic concepts of binding in XAML. As you can see, the binding source can be any property of any CLR object. The binding object connects this source to the binding target, which must be a dependency property of some object that inherits from FrameworkElement (all the standard
controls inherit from this base class, and just about every property of these controls is a DependencyProperty object.)

introbinding

Figure 1. The Binding object connects the binding source and target.

Although you can generally work blissfully unaware of this fact, when you use a binding in XAML you’re actually creating an instance of the Binding class, setting various properties. XAML provides a markup extension that hides this fact, as you’ll see, but all the same, you’re working with a Binding class instance.

TIP: If you want to create a binding in code, you’ll always need to create an
instance of the Binding class, and set its various properties to match the
properties you would otherwise set in XAML markup.

The flow shown in Figure 1 indicates that binding can work in multiple directions. By setting the Mode property of the Binding instance, you can indicate whether you want the data to move in one direction whenever changes are made to the source, in one direction only once, in two directions, or not at all.

Value Converters

The Value Converter block in Figure 1 represents an instance of a class that implements the System.Windows.Data.IValueConverter interface. You’ll often need to use a value converter, especially if you want to do all of your binding declaratively, in the XAML markup. Imagine scenarios like these, in which value converters become necessary:

  •  You want to select a customer from a ListBox, and display the combined FirstName and LastName fields in a TextBlock.
  •  You want to select a number value, and use that value to set the BorderThickness of a Border control. You can’t simply bind the number to the property, because the BorderThickness property of a Border is a Thickness object.

There are, obviously, infinite reasons to use a value converter, but unless you perform data binding declaratively (in the XAML markup, that is) there’s no reason to use one. But if you would like to simplify your applications and reduce the amount of code you must maintain, using declarative binding is a truly useful tool, and it requires value converters in order to be fully useful.

This post is an excerpt from the online courseware Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

  Robert Greenis is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Visual C#: Navigation in Applications

In most client applications, users can have any number of windows open at the same time. In Outlook, you can have the Inbox, Calendar, Tasks, and Contacts open at the same time. You can have multiple messages, appointments, tasks and contacts open at the same time. You are limited solely by your tolerance for navigating amongst large numbers of windows.

When you create a Windows Forms Application project in Visual Studio, the first thing you see is a form. Often this will be your startup form. You then add any number of forms to the application. Each form is a window and it serves a purpose, whether it is data entry or reporting or a splash screen or navigation. Whether users navigate by selecting a menu item or clicking a button, the application displays a new form in a new window. Web applications take the opposite approach. Typically, you will have one window open, and that is the browser. As you navigate within a site, you load a different page in the browser and you have one page open at a time. This is not always the case, but it is true much more often than not.

In a WPF application, you can choose either of these navigation paradigms. The WindowNavigationDemo sample application consists of three windows. The MainWindow.xaml file defines the application’s startup window. It contains buttons to display the other two windows, defined in Window1.xaml and Window2.xaml. Both of these windows can be open at the same time, as
shown in the figure below.

nav_in_application

Figure above, this application uses window-based navigation.

When you create an application based on the WPF Application project template, Visual Studio assumes that you will use windows-based navigation. It sets the startup window to MainWindow.xaml.

If you want to use page-based navigation, and make your application look and feel more like a Web application, you need to use pages rather than windows. You should also consider using hyperlinks rather than buttons.

The Page class is similar to the Window class. Each is a container and can contain a single element, such as a StackPanel, DockPanel, or Grid. A primary difference between a window and a page is that a page is designed to be navigated to.

A page can be hosted in a Window, a NavigationWindow, a Frame, another page, or the browser. Because it is not a standalone container, it has a smaller set of properties than a window.

The Page class contains several properties, including the following:

  • Background: Determines the background for the page
  • Foreground: Determines the default foreground for the page. All elements in the page will have this foreground by default.
  • FontFamily and FontSize: Determine the default font family and size for the page. All elements in the page will have this font size and family by default.
  • ShowsNavigationUI: Determines whether the page displays back and forward buttons.
  • Title: Sets the name of the page used in the navigation history.
  • WindowHeight and WindowWidth: Determine the height and widthof the window that hosts the page.
  • WindowTitle: Determines the title of the window that hosts the page.

The NavigationWindow class represents a window with built-in navigation support. This class derives from the Window class and includes the ability to display content and navigate. The content can be any .NET Framework object or HTML page, but typically the content will be in a page.

The NavigationWindow object supports not only navigation but the navigation history. Some of the properties of the NavigationWindow class are:
BackStack and ForwardStack: Return an IEnumerable you can use to enumerate the entries in the window’s back and forward navigation history.

  • CanGoBack and CanGoForward: Indicate whether there is at least one entry in the back and forward navigation history.
  • CurrentSource: Gets the uniform resource identifier (URI) of the content that was last navigated to.
  • ShowNavigationUI: Determines whether a NavigationWindow shows its navigation buttons.
  • Source: Gets or sets the uniform resource identifier (URI) of the current content, or the URI of new content that is currently being navigated to.

This post is an excerpt from the online courseware Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Windows Presentation Foundation Using Visual C# 2010: The Resources Dictionary

Every element in your application provides a Resources property (this includes every control and container), which is actually a Dictionary in which the key is a string, and the value is a resource. In other words, every element contains a collection of resources, indexed by a string key name.

Although every element can contain its own defined resources, most of the time it’s easiest to place resources at the window level. Doing that makes the available to all the controls in the window. Every element always has access to all its resources, and the resources of its parents (all the way back up to the application level), so if you want to share resources between elements, the higher you place the resources, the easier it will be to do so.

Imagine that you want to create a LinearGradientBrush instance that you will use as the background for several controls on a page. Rather than defining it in the content of each individual element, you can extract the gradient in the resources collection for the container (in this example, a user control) instead. The sample user control, IntroResource.xaml, includes a very simple resource. The syntax in the sample (displayed in Figure 1) looks like the following:

gradient_figure1Figure 1. The sample gradient.

TIP: Although the examples here are all based on user controls for the purposes of making the demonstration easier to navigate, you can also define resources at any level. Often, in WPF applications, you’ll define resources at the window level, in the Window.Resources element.

The differences between this definition and what you would see if you had defined the gradient brush for each individual element are:

  • The resource appears inside the UserControl.Resources element.
  • The resource includes an x:Key attribute, defining the key for the resource. Remember that the collection of resources is actually a Dictionary, and every item in a dictionary must contain a unique key that identifies it.

NOTE The x: prefix on the Key attribute indicates that it’s in the XAML  namespace, rather than the WPF namespace. You’ll use this key to refer to the resource, whenever you want to use it. It doesn’t matter what you call the resource, as long as you use this Key attribute value to refer to the resource.

TIP: Name your resources based on their functionality, not their contents. The uses won’t change as often as the particular implementation details, and it will be easier to select resources if you name them based on their usage.

To use the resource, you must be able to refer to it. To do this, use a markup extension, delimited with curly braces:

You may have seen the markup extension syntax used when performing property binding, or in other contexts. In general, XAML uses markup extensions whenever it needs to be able to set a property in a non-standard way. In this case, the StaticResource keyword indicates that when XAML needs to retrieve and set the Background property of the Border element, it
should look for a resource whose x:Key attribute is BackgroundBrush, and use
the definition it finds there.

Would you use a resource in a case like this, in which you only consume the resource once? It certainly doesn’t make the XAML any more efficient, or more compact. On the other hand, it does make it easier to isolate the layout details—by placing all the formatting information in one place, it’s easier to keep track of, and maintain, the look of your application.

You may be wondering about the word “Static” in the markup extension. Why Static? Is there a Dynamic resource, as well? WPF provides both static resources, which are applied only once, when you first create the window, and dynamic resources, which are reapplied if the resource changes. Dynamic resources (using the DynamicResource markup extension) use slightly more overhead, but allow you to change the content of the resource at runtime. Static resources are simpler, and provide much of the functionality you’ll need.

NOTE If you programmatically change a feature of an existing static resource at runtime (for example, if you change a color, or some other property of the existing resource), WPF automatically updates the display to match. Dynamic resources allow you to replace the entire resource with another at runtime. In general, static resources provide the functionality you’ll need for most applications.

WARNING! It’s important that you define the static resources before you attempt to use them in the markup. Unlike most modern programming languages, the order of appearance within the source file is a concern—you cannot use a resource before it has been declared. The XAML parser reads content from start to finish, and expects to find the definition for a resource at the time the XAML attempts to use the resource. This isn’t true for dynamic resources, however. You can define dynamic resources after they’re used, and the XAML parse can still find them.

This post is an excerpt from the online courseware Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Radio Button Control – Visual C#

The RadioButton control works much like the CheckBox control—it provides the same properties, and the same events. The big difference between the RadioButton and CheckBox controls is that RadioButton controls are grouped by their container. Within a single container, you can generally only select one RadioButton control. If you place multiple RadioButton controls into multiple containers, you can select one RadioButton control from each container.

You can override this behavior using the GroupName property of the control. You can set this string value to create more than one group per container, or to create a single group that spans multiple containers. To demonstrate this behavior, select the RadioButton tab in the sample application, shown in Figure 1.

TIP: There’s no need to specify a GroupName property for a RadioButton control unless you want to override the default behavior.

radiobuttoncontrl

Figure 1. RadioButton controls normally allow you to select only one per
container; override the behavior with the GroupName property.

The markup for the sample page looks like the following:

If you try out the demonstration, you’ll see that you can only select a RadioButton control from the group named Group 1, because they’re all in the same container. You can select only a single item from the group named Group 2, again, because they’re in the same container. You can also select one item from the group named Group 3, because these items have their GroupName property set to the same text (the text is arbitrary, and it’s set to
Group3 in the example). Because these controls share the same group name, and because they have a group name set, you can select multiple RadioButton controls within a single container.

In contrast, the right-hand Border control contains multiple CheckBox controls. Nothing keeps you from selecting as many CheckBox controls as you like. That’s the point: When you use RadioButton controls, you intend for users to select only one per group. When you use CheckBox controls, you intend users to select multiple items.

NOTE This sample uses a StackPanel control as the container for the
groups of RadioButton controls. You may also want to investigate
the GroupBox control, which not only groups the controls but
also adds a caption describing the group. The GroupBox control is,
effectively a simple container with a caption added.

This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.