Powered by MSDN

US - English
NEW! Silverlight 5 is available Learn More

  • RomainP

    RomainP

    Member

    39 Points

    44 Posts

    Re: Custom control : databound ListBox with checkboxes

    Jan 08, 2009 10:32 PM | LINK

    Binding the list to the code-created checkboxes... that's brilliant!

    Thanks a lot meykih, this is exactly what I was looking for. It is also much better than before, because instead of calling VisualTreeHelper to access the CheckBoxes, we can now get to them fast and easy.

    I only had to make one change though: with the binding you had, I couldn't find a way to access the actual databound object. The "content" property of the checkbox would just be set to the string representation of the field.

    	Binding binding = new Binding(control.CheckBoxContentProperty);
    	binding.Source = item;
    	binding.Mode = BindingMode.OneWay;
    	checkbox.SetBinding(CheckBox.ContentProperty, binding);

    Did I miss something? Instead I now use the following:

     
    	checkbox.DataContext = item;
    	Binding binding = new Binding(control.CheckBoxContentProperty);
    	binding.Mode = BindingMode.OneWay;
    	checkbox.SetBinding(CheckBox.ContentProperty, binding);
     

    This way I can iterate over the checkboxes and get the object they are bound to.
    I use it in the GetCheckedItems() method:

     
    	foreach (CheckBox checkbox in this.Items)
    	{
    		if (checkbox.IsChecked.Value)
    		{
    			// here the databound object is checkbox.DataContext
    		}
    	}
    
     

    What do you think of the change?
    Thanks again for your help, I guess we finally have a generic CheckBoxList control!

    Romain