views:

49

answers:

1

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 field 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>
A: 

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.

shannon.stewart
WebContext implies you're using Silverlight and RIA services. The question was about WPF...
Alex Paven
Oops, good catch. You could replace the WebContext with the WPF version. Maybe the Threading.Thread.CurrentPrincipal.
shannon.stewart
He's on the right track though. This is a good way of doing it. I would have a "SecurityService" class with a method to return the current user's roles, etc.
Rick Ratayczak