Skip to Main Content
Programming WPF, 2nd Edition
book

Programming WPF, 2nd Edition

by Chris Sells, Ian Griffiths
August 2007
Intermediate to advanced content levelIntermediate to advanced
864 pages
25h 52m
English
O'Reilly Media, Inc.
Content preview from Programming WPF, 2nd Edition

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>

  <DockPanel DataContext="{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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C#, 4th Edition

Programming C#, 4th Edition

Jesse Liberty
Programming C# 10

Programming C# 10

Ian Griffiths

Publisher Resources

ISBN: 9780596510374Supplemental ContentErrata Page