Reputation: 2364
I am working with a TabControl in XAML,
however I only want certain TabItems to be available depending on the user.
Admins = 1
therefore should have full access to the TabControl,
Non admins = 0
therefore should only have specific tabs available.
How can I hide specific tabs depending on the user?
Thanks.
Upvotes: 1
Views: 3012
Reputation: 132558
There are many ways of doing this, and I suppose which one you use depends on where the IsAdmin
flag is stored
My personal preference is a DataTrigger
which is based off a static User
object which is set when the user first logs in
<Style TargetType="{x:Type TabItem}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Value="True" Binding="{Binding IsAdmin, Source={x:Static local:Settings.CurrentUser}}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
Settings
would be a static class that contains a CurrentUser
property that is set when the application starts up and the user logs in. CurrentUser
has a boolean property called IsAdmin
Upvotes: 2
Reputation: 1995
Create a value converter:
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool myValue = (bool)value;
if (myValue)
return Visibility.Visible;
else
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Add this as a resource to your XAML:
<local:BooleanToVisibilityConverter x:Key="visibilityConverter"></local:VisibilityConverter>
Assume that your property that shows if a user is admin named IsAdmin
<TabItem Visibility={Binding Path=IsAdmin, Converter={StaticResource visibilityConverter}}">
I think that is all.
Upvotes: 1
Reputation: 70728
You could hide all tabs once the application loads and then do something simple like the following to show each tab depending on the users access level:
if (userId == 1) {
foreach (var item in tabControl.Items) {
item.Visibility = Visibility.Visible;
}
} else if (userId == 0) {
tabControl.Items[TableControlYouWantVisibile].Visibility = Visibility.Visible;
}
Upvotes: 0