2

i would like to enable/disable buttons according to the current active userlevel. i have a property in the MV for the current userlevel:

public int CurrentUserLevel
    {
        get { return _CurrentUserLevel; }
        set
        {
            if (_CurrentUserLevel == value)
                return;
            _CurrentUserLevel = value;
            RaisePropertyChanged("CurrentUserLevel");
        }
    }

how can i enable/disable the button if this value is >=x?

1 Answer 1

5

You'll need to create a property in your ViewModel, for which the Button's IsEnabled property can bind to. Make sure that the new property's PropertyChanged event is raised whenever the CurrentUserLevel is changed.

public int CurrentUserLevel
{
    get { /*...*/ }
    set
    {
        /*...*/
        RaisePropertyChanged("CurrentUserLevel");
        RaisePropertyChanged("IsAllowedToDoSomething"); //dependant property
    } 
}

public bool IsAllowedToDoSomething
{
    get { return CurrentUserLevel > 1; }
}

And in your XAML:

<Button IsEnabled="{Binding IsAllowedToDoSomething}" Content="Click me!" />
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer. so if i have 5 userlevels (1 to 5), i'll need to create 5 properties right? for each level one.
One for each type of binding you want to create on a Button, yes. MVVM ViewModels contain a lot of these "helper" properties, which make binding from the View more natural.
Perhaps we can use binding converters and a single property instead of secondary properties. Converters accept a parameter, so maybe a single converter will be required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.