views:

1534

answers:

1

I have simple issue setting a two-way databinding of a checkbox in Silverlight 3.0. It must be a no-brainer but probably I forgot my brain home today...

I defined a Model class to represent my .. 'data'. I implemented the INotifyPropertyChanged interface to enable the UI to see when the data changes.

public class Model : INotifyPropertyChanged
{
    private bool _value;
    public bool Value
    {
        get { return this._value; }
        set
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            this._value = value;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Next I put a checkbox and a button on the .. 'form' :

    <StackPanel Orientation="Horizontal">
        <CheckBox x:Name="check" IsChecked="{Binding Value, Mode=TwoWay}" Content="SomeLabel"/>    
        <Button Click="Button_Click" Content="Test" />
    </StackPanel>

Then I supplied the data in the constructor :

    public MainPage()
    {
        InitializeComponent();

        this.DataContext = new Model() { Value = true };
    }

The issue is that you have to click twice on the checkbox for it to check/uncheck unless I de-implement the INotifyPropertyChanged. If de-implement it however, then the UI doesn't notice if I change the underlying data.

If I remove the Mode=TwoWay bit from the IsChecked binding expression then also the UI won't notice the underlying data change even if the Model is implementing the interface.

How can I do to :

  1. Have the checkbox bound to the data at startup
  2. Have the checkbox IsChecked change to modify the underlying data
  3. Have the checkbox detect the underlying data change and update itself?
+4  A: 

You've got a sequencing error in your set property procedure, you need to assign to _value before notifying the change :-

    set
    {
        this._value = value;
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs("Value"));

    }
AnthonyWJones
Thanks!!! It worked. I told you I forgot my brain home today :))
Andrei Rinea