views:

976

answers:

0

I have a ListBox whose DataTemplate is created in code using 3 FrameworkElementFactory objects(A StackPanel with 2 appended children(CheckBox and TextBox)). The item object in the collection that is bound to the ItemsSource of the ListBox is basically the same type of Item object that you would typically see with any type of ListControl. What I'm trying to do is bind the CheckBox's IsChecked property in the DataTemplate to a boolean property on the Item object. The ListBox supports 3 modes, single select, multiselect, and multicheck. The mode I'm trying to implement is multicheck so that the IsChecked property of the CheckBox is bound to the Selected property of the item object. This creates a behavior where the item is only considered selected when the CheckBox's IsChecked property on the ListBoxItem is true, not when the WPF ListBoxItem's IsSelected property is true. What should happen is that the boolean property on the data object should be bound to the IsChecked property, and when the IsChecked property is changed the Selected property on the item object will update, and will thus update a SelectedItems collection behind the scenes.

Here is some simplified code that I have just described.

ListBox innerListBox = new ListBox();
//The ItemsSource of the ListBox being set to the collection of items            
this.innerListBox.ItemsSource = this.Manager.ItemManagers;
this.innerListBox.ItemTemplate = this.GetMultipleCheckTemplate();    

public System.Windows.DataTemplate GetMultipleCheckTemplate()  
{  
    DataTemplate dt = new DataTemplate;  

FrameworkElementFactory factorySP = new FrameworkElementFactory(typeof(StackPanel));  

FrameworkElementFactory factoryCB = new FrameworkElementFactory(typeof(CheckBox));      
factoryCB.SetBinding(CheckBox.IsCheckedProperty, new Binding("Selected");  

RoutedEventHandler clickHandler = new RoutedEventHandler(ItemCheckBox_Click);  
factoryCheckBox.AddHandler(CheckBox.ClickEvent, clickHandler, true);   

factorySP.AppendChild(factoryCB);  

FrameworkElementFactory factoryTB = new FrameworkElementFactory(typeof(TextBlock));    
factoryTB .SetBinding(TextBlock.TextProperty, new Binding("Description");  

factorySP.AppendChild(factoryTB);   

template.VisualTree = factorySP;    
return template;  
}

There is some code that I'm not including that is the event handler on the CheckBox. If there is a multiple selection on the Wpf ListBox, then all of the CheckBoxes in the range would be toggled to the value of the CheckBox that was clicked. I can manually set the Selected property on the Item to the IsChecked property of the sender and everything works fine, I would however think that databinding should just work and I wouldn't have to do this manually. Would the databinding in this case be asynchronous or do I need to do something explicitly?