Password Sample

This sample demonstrates the ChangedHandler, making conditional decisions and using static resources. This shows that instead of "building up more tools" we can instead "break down the tools" to get the job done. The problem was that the old tools weren't composable so we needed to write new ones to handle every new situation.

We want to have a status area whose text contents depend on the contents of another element a TextBox containing a password. We know the password. If the password is right, we want the status to reflect that. Furthermore we want the background of the status to be green or red depending on whether the password is correct. This is not rocket science but the goal is to add just this little bit of functionality to the static XAML without writing any code-behind. On with the XAML. Notice the two syntax methods. The path syntax is more C#-like, the element syntax is more XAML-like. They both compile to the same to the same thing; use which ever you need or prefer.

<UserControl
    x:Class="Markup.Programming.Samples.PasswordSample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="http://markupprogramming.codeplex.com/markup/programming"
    Height="300" Width="300">
    <Grid>
        <StackPanel>
            <StackPanel.Resources>
                <SolidColorBrush Color="Red" x:Key="RedBrush"/>
                <SolidColorBrush Color="Green" x:Key="GreenBrush"/>
            </StackPanel.Resources>
            <TextBlock FontSize="20" Text="The password is: xyzzy"/>
            <TextBox FontSize="20" Name="Password"/>
            <Grid>
                <TextBlock FontSize="20" Foreground="White" FontWeight="Bold"/>
 
                <p:Attached.Operations>
                    <p:ChangedHandler Value="{Binding Text, ElementName=Password}">
                        <p:Set Var="$redBrush" Value="{StaticResource RedBrush}"/>
                        <p:Set Var="$greenBrush" Value="{StaticResource GreenBrush}"/>
                        <p:Script>
                            /* Check if the new value is right and set the status and color. */
                            var $isRight = @EventArgs.NewValue == "xyzzy";
                            @AssociatedObject.Children[0].Text = $isRight ? "On the money!" : "Guess again.";
                            @AssociatedObject.Background = $isRight ? $greenBrush : $redBrush;
                        </p:Script>
                    </p:ChangedHandler>
                </p:Attached.Operations>
 
            </Grid>
        </StackPanel>
    </Grid>
</UserControl>
 

@hash=81cd35d5@

Last edited Mar 31, 2011 at 6:14 AM by jrs, version 13

Comments

No comments yet.