WebContext获取用户登录状态显示隐藏控件

之前接触了RIA Services Business Application的项目模板,这个项目模板为我们提供了用户验证的模块,它是基于Membership的。我们经常需要根据当前的用户是否登录隐藏和显示控件。我们新建一个RIA Service Business Application,打开App.xaml.cs,其中有一段下面的代码:

private void Application_Startup(object sender, StartupEventArgs e)
        {
            // This will enable you to bind controls in XAML files to WebContext.Current
            // properties
            this.Resources.Add("WebContext", WebContext.Current);
 
            .......
        }
将当前上下文对象添加到ResourceDictionary,以资源的方式的存储。你可以通过StaticResource,可以很容易的绑定。WebContext.Current.User.IsAuthenticated是一个Bool类型,我们需要将True/False转换Visibility.Visible/Visibility.Collapsed。这里需要编写一个Converter:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
 
namespace ASoft.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();
    }
  }
}
在XAML代码里面:
<UserControl
  ...
  xmlns:converters="clr-namespace:ASheng.Converters;assembly=ASheng.Converter">
 
<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}}"/>

你可能感兴趣的:(context)