The Grayzone

Binding to WebContext.Current in XAML

When using the RIA Services Business Application template in VS 2010 I noticed that the WebContext.Current object is added to the applications ResourceDictionary:

private void Application_Startup(object sender, StartupEventArgs e)
{
  this.Resources.Add("WebContext", WebContext.Current);
  ...
}

As this is now stored as a resource you can easily bind to it, using the StaticResource extension. I’ve used it with a simple Value Converter to show/hide options depending on whether the user is Authorised, e.g.:

<UserControl
  ...
  xmlns:converters="clr-namespace:theGrayZone.Converters;assembly=theGrayZone.Common">

<UserControl.Resources>
  <converters:BoolToVisibilityConverter x:Key="BoolVisibilityConverter"/>
</UserControl.Resources>

<HyperlinkButton NavigateUri="/Search" TargetName="ContentFrame" Content="Search" Visibility="{Binding Path=User.IsAuthenticated, Source={StaticResource WebContext}, Converter={StaticResource BoolVisibilityConverter}}"/>

using the following as my converter:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace theGrayZone.Converters
{
  public class BoolToVisibilityConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return (bool)value ? Visibility.Visible : Visibility.Collapsed;
    }

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

Share this: