Jack Miller
Jack Miller

Reputation: 325

Disable and enable buttons using variables

I have a button that will be enabled or disabled with the use of a bool, I am using MVVM:

Button:

<Button x:Name="backButton" Content="Back" Command="{Binding BackCommand}" 
IsEnabled="{Binding Path=BackBool, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>

The bool:

    public bool BackBool
    {
        get { return isBackEnabled; }
        set
        {
            this.RaisePropertyChangedEvent("isBackEnabled");
            isBackEnabled = value;
            this.RaisePropertyChangedEvent("isBackEnabled");
        }
    }

I've added the bool to the variable watch and it updates correctly changing to true when the buttons should be enabled.

However the Buttons them selves do not update and always stay disabled.

Am I missing something?

Upvotes: 0

Views: 2401

Answers (2)

Anurag
Anurag

Reputation: 36

Modified version of your code

Button:

<Button x:Name="backButton" Content="Back" Command="{Binding BackCommand}" 
IsEnabled="{Binding Path=BackBool, Mode=OneWay}"/>

The bool:

public bool BackBool
{
    get { return isBackEnabled; }
    set
    {
        isBackEnabled = value;
        this.RaisePropertyChangedEvent("BackBool");
    }
}

Upvotes: 2

Raise PropertyChanged with the name of the property whose value changed. You gave the Binding in the XAML exactly one applicable piece of information: The string "BackBool".

public bool BackBool
{
    get { return isBackEnabled; }
    set
    {
        isBackEnabled = value;
        this.RaisePropertyChangedEvent("BackBool");
    }
}

Also, omit the no-op flags from the binding. Never set an attribute on a binding until you've looked it up on MSDN and found out what it does. Saves a lot of scolding on Stack Overflow, and a lot of your own time testing changes that can't make any difference.

<Button 
    x:Name="backButton" 
    Content="Back" 
    Command="{Binding BackCommand}" 
    IsEnabled="{Binding Path=BackBool}"
    />

Upvotes: 4

Related Questions