Using Resources
You’ve seen how you can affect the properties of a single control, but in an application with more than one control, you wouldn’t want to have to set each control’s properties individually. That’s where resources come in. You define a resource for an entire WPF application, where it can be used by any appropriate control.
To see how this works, you’ll add another Label
and Button
to your Hello WPF example. Drag a Label
control to somewhere near the upper-left corner of the window. Drag a Button
control next to the Say Hello button. You can see in the Design window that the new controls have the Windows standard appearance, not the custom appearance that you gave the two older controls. In some cases, that’s fine, but most of the time, you’ll want all the controls in your application to have a consistent appearance.
For the Label
, change its name to lblTop
, and set its Content
property to “WPF Test”. You won’t do anything programmatically with this label; it’s just for demonstration purposes. You might as well give the button something to do, though. Change its Name
to btnCancel
, and its Content
property to “Cancel”. Double-click the button to create its event handler, and add the following code:
this.Close( );
In a WPF application, you use the Close( )
method to end the application, rather than Application.Exit( )
, as you would in Windows Forms.
To get the controls of each type to have the same appearance, you’ll define a Style
element as a resource. Resources are generally ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.