views:

752

answers:

2

Hey there,

I am using the Model View View-Model pattern for a WPF app. I have a ViewModel (set as a pages DataContext) with two properties, one of which is an Entity with a PropertyChanged event. In the event handler i set the value of the other property (a boolean) to some value.

Now the Button and TextBox properties are binding fine on first load and the PropertyChanged event is firing and doing its thing. However the Button's IsEnable property doesn't update to reflect the change in the property its bound to.

The ViewModel looks sorta like this:

public sealed class CustomerPageViewModel
{ 
    public Customer Customer
    {
        get;
        set;
    }

    public bool Editing
    {
        get;
        private set;
    }   

    private void Customer_PropertyChanged(object sender,
        System.ComponentModel.PropertyChangedEventArgs e)
    {
        Editing = true;
    }
}

And the xaml sorta looks like this:

<TextBox Text="{Binding Customer.Name}" />   
<Button Content="Save Changes" IsEnabled="{Binding Editing}" />

How can i get the Button to update its IsEnable property when i change the underlying property in the ViewModel?

+1  A: 

Is that your ViewModel's actual code? If so, your problem is that your ViewModel doesn't implement INotifyPropertyChanged. WPF can't know that your "Editing" VM property has changed so it's not updating the button's binding.

Matt Hamilton
oops, your right. I implemented the interface and raise the event now when Editing is changed. That was all that was needed. Thank you.
andrej351
A: 

When the code sets Editing to true, that doesn't appear to trigger the PropertyChanged event, so the Button has no idea that it should update the binding for IsEnabled. Try something like this:

public sealed class CustomerPageViewModel : INotifyPropertyChanged
{ 
    public Customer Customer
    {
        get;
        set;
    }

    private bool editing = false;
    public bool Editing
    {
        get { return editing; }
        private set
        {
            editing = value;
            Customer_PropertyChanged(this, new PropertyChangedEventArgs("Editing");
        }
    }   

    public event PropertyChangedEventHandler PropertyChanged;
    private void Customer_PropertyChanged(object sender,
        System.ComponentModel.PropertyChangedEventArgs e)
    {
        PropertyChanged(this, e);

        if(!e.PropertyName.Equals("Editing"))
        {
            Editing = true;
        }
    }
}

Note that you must verify that Editing didn't cause the PropertyChanged event to fire, else you'll get an infinite loop.

Andy