Free Exam Guide 70-511, WPF: ContextMenu as a Static Resource

Ok, back to studying for the 70-511 exam.  So much to do.

In the last blog post about Windows Presentation Foundation and static resources

Free Study Guide for Exam 70-511: Defining Static resources
  • We covered about why Static Resources and why Dynamic Resources
  • Static Resources are used when the software will not modify the value of the resource after it is referenced for the first time.
  • Dynamic Resources you might use when the software/app will be modified to meet unknown conditions after the software/app is run

Dynamic Resources concepts are used after the software/app starts running.  This means that you cannot view the dynamic resource value when you are just looking at the XAML Design Pane like you can with Static Resources.  What kind of things do you expect to change after the application starts?  On Windows the end user can easily change the screen size, in this case you may want to increase the size of your controls, add more features or change font sizes in the textboxes.

Here is an example using a ContextMenu as a static resource..  In this example if you copy and paste the code into your WPF XAML, and then right click on the textbox you will see a context menu show up. 

The x:Key for the ContextMenu is “SpaceAliens”, it is then used in the <Grid> as a static resource.  As point of good practice it is better to use data binding, but if you are new to WPF, XAML or Windows Phone 7 Development, then the term “Data Binding” is something you might still be sorting out in your mind.  The way that the MenuItems are added here is more like the way you might do it in MS Access or similar kind of database design tools.

 <Window x:Class="PlanetCitizens.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ContextMenu x:Key="SpaceAliens">
            <MenuItem Header="Martian"/>
            <MenuItem Header="Venusian"/>
            <MenuItem Header="Jovian"/>
        </ContextMenu>
        
    </Window.Resources>

        <Grid>
        <TextBlock Height="30" Width="100"
                   Text="Right Click This textbox"
                   Background="LightBlue"  
                   ContextMenu="{StaticResource SpaceAliens}" Margin="0,0,402,282" />
        <Button Content="Button" Height="23" 
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Margin="34,84,0,0" 
                Name="button1" 
                Width="75" />
    </Grid>

Give it a try, if you do, then future blog entries  about Dyanmic Resources will make more sense.

 

NNNN