Resources
Resources are named chunks of data defined separately from code and bundled with your application or component. .NET provides a great deal of support for resources, a bit of which we already used when we referenced tom.png from our XAML button earlier in this chapter. WPF also provides special support for resources scoped to elements defined in the tree.
As an example, let's declare some default instances of our custom
Nickname objects in XAML (see Example 1-30).
Example 1-30. Declaring objects in XAML
<!-- Window1.xaml --> <Window ...xmlns:local="clr-namespace:DataBindingDemo"/> <Window.Resources> <local:Nicknames x:Key="names"> <local:Nickname Name="Don" Nick="Naked" /> <local:Nickname Name="Martin" Nick="Gudge" /> <local:Nickname Name="Tim" Nick="Stinky" /> </local:Nicknames> </Window.Resources> <DockPanelDataContext="{StaticResource names}"> <TextBlock DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock VerticalAlignment="Center">Name: </TextBlock> <TextBox Text="{Binding Path=Name}" /> <TextBlock VerticalAlignment="Center">Nick: </TextBlock> <TextBox Text="{Binding Path=Nick}" /> </TextBlock> ... </DockPanel> </Window>
Notice the Window.Resources,
which is property element syntax to set the Resources property of the Window1 class. Here we can add as many named
objects as we like, with the name coming from the Key attribute and the object coming from the XAML elements (remember that a XAML element is just a mapping to .NET class names). In this example, ...