2

I am trying to figure out how to show/hide a navigation link based on the users role. Currently I am testing to see if the user is logged in, and that works great - here's my code:

<HyperlinkButton x:Name="AdminLinkButton" Visibility="{Binding User.IsAuthenticated, Source={StaticResource WebContext}, TargetNullValue=false, Converter={StaticResource VisibilityConverter}}" Style="{StaticResource LinkStyle}" NavigateUri="/Admin" TargetName="ContentFrame" Content="{Binding Path=Strings.AdminPageTitle, Source={StaticResource ApplicationResources}}"/>

However, now I need to change it to make sure the Admin button is only visible if the user is in the "Admin" role.

Anybody have a suggestion?

Thanks,

Scott
  • 874
  • 3
  • 12
  • 36

3 Answers3

2

You need to add the loggedin eventhandler in the mainpage like so: Authentication.LoggedIn += LoggedIn_Event;

In the LoggedIn_Event method, check whether the user is in the required role:

private void LoggedIn_Event(object sender, AuthenticationEventArgs e){
    if (e.User.IsInRole("Required Role")){
        AdminLinkButton.Visibility = System.Windows.Visiblity.Visible;
     }
    else
    {
        AdminLinkButton.Visibility = System.Windows.Visiblity.Collapsed;
    }
}

And remember to handle the LoggedOut_Event and disable the control.

KMarto
  • 300
  • 2
  • 23
1

One option is to pass a parameter via the ConverterParameter which will identify the type of user associated with determining the result returned from the converter.

ConverterParameter='admin'

Another option to avoid the String limitation imposed by the ConverterParamter is to store the type of user logged in via a Singleton or other static means which the converter can query to know what user is logged in and thus return the resulting visibility. If you must access the data within XAML you can do so by making use of x:Static.

ConverterParameter={x:Static namespace:LoggedInUserType}
Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
0

There are a couple of ways to do this, some ways more of a hack than others:

  1. create one converter to do the whole job of converting whether the user is in a role to a Visibility value
  2. chain multiple converters (follow the link in the answer) with each converter doing one part of the conversion

Approach #1 will get you there, but ultimately is a bad approach because it leads to a plethora of specialized converters which can be a PITA to maintain.

Approach #2 is more work but overall a better and more maintainable approach.

Community
  • 1
  • 1
slugster
  • 49,403
  • 14
  • 95
  • 145