views:

265

answers:

1

Hello,

I've just come across this problem with my checkbox data binding. The scenario is:

When I initialize the user interface (start the application), the checkboxes are unchecked, although the property they are bound to is set to true. When I click the checkbox, the property is set to false, but the checkbox is still shown as unchecked. From now on, the data binding works as expected and the checkbox is correctly synched with the binding property.

Here's my XAML code:

<ItemsControl ItemsSource="{Binding Path=DisplayTypes}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type Presentation:TypeDisplayPair}">
            <CheckBox IsChecked="{Binding Display}" Margin="3">
                <TextBlock Text="{Binding Type}" Foreground="{Binding Color}" />
            </CheckBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

And my view model:

public class TypeDisplayPair : BaseViewModel
{
    private bool display;
    private readonly Brush color;

    public TypeDisplayPair(string type, bool display)
    {
        Display = display;
        Type = type;
        color = BrushGenerator.GetRandomSolidColorBrush();
    }

    public string Type { get; set; }

    public bool Display
    {
        get { return display; }
        set
        {
            display = value;
            this.FirePropertyChanged(x => x.Display);
        }
    }

    public Brush Color
    {
        get { return color; }
    }
}

Any suggestions are appreciated, as I've spent too much time debugging this and I've run out of ideas.

+2  A: 

The code you provided is perfectly correct, you initialization problem probably comes from the way you assign the DataContext. I've tried the following:

 public Window1()
 {
  DataContext = this;
  DisplayTypes = new ObservableCollection<TypeDisplayPair>()
  {
   new TypeDisplayPair("Alpha", true),
   new TypeDisplayPair("Beta", false)
  };

  InitializeComponent();
 }

and it works as expected.

Mart