Using roles/permission to enable/disable content in the view
I'm working on an WPF application using the mvvm-light framework. I'm new to both of these.
I have a form that allows a user to edit a record in a database. Admin users need to be able to update a fiel开发者_运维百科d that should be read-only for other users. It would be easy for me to put this enable/disable code in the view's code-behind but my understanding is that this belongs in the ViewModel.
How do I hide this textbox without putting the code in the View?
Thanks in advance.
<TextBox Grid.Column="1" Grid.Row="0" HorizontalAlignment="Left" Name="uxMallNum" VerticalAlignment="Center"
Width="100" Height="25" MaxLength="50" Validation.ErrorTemplate="{DynamicResource validationTemplate}" Style="{DynamicResource textStyleTextBox}">
<TextBox.Text>
<Binding Path="MallNumber" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" >
<Binding.ValidationRules>
<local:StringRangeValidationRule MinimumLength="1" MaximumLength="50"
ErrorMessage="Mall Number is required and must be 50 characters or fewer." />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
I've built a converter for this type of function, although I'm not sure if there's a better way.
public class AdminVisibilityConverter : IValueConverter
{
#region Methods
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isAdmin = WebContext.Current.User.IsInRole("Admin");
return isAdmin ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Then I add the converter to the visibility property of a control.
<toolkit:AccordionItem Tag="#ManageAnnouncements" Visibility="{Binding Source=User, Converter={StaticResource AdminVisibilityConverter}}">
You could pass in the roles, or usernames, in the parameter of the converter, but my instance didn't need it.
精彩评论