To expose the new command to the user, we just add a button to the LogOnControl.
<Button
    Command="{Binding LogOff}">Log Off</Button>
Run the client and you'll be able to log on and off. Only one of the buttons will be enabled at a time.

We can make it look a little better. There is no need to show both buttons. We can show the Log On button only when you are logged off, and the Log Off button when you are logged on. Do this with a pair of value converters.
public class VisibleWhenTrueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(Visibility) && targetType != typeof(Visibility?))
            throw new InvalidOperationException("VisibleWhenTrueConverter can only be used with Visibility properties.");

        return ObjectToBoolean(value) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    private static bool ObjectToBoolean(object value)
    {
        if (value != null && value is bool)
            return (bool)value;
        return false;
    }
}
VisibleWhenFalseConverter is similar. Create a boolean property in the view model that is true when a user is logged on, and use these two value converters to bind that property to the Visibility of both buttons. Now the user sees just one button at a time, and can log on and log off.

Next: Practice 3: Create a negative fact

Last edited May 15, 2011 at 5:17 AM by MichaelLPerry1971, version 4

Comments

No comments yet.