I have two WPF list boxes. One is a list of lists (actually a List of ObservableCollection), the other is a list of all known instances of ‘Thingy’.
Here’s the datatemplate I’m using for the ‘thingy’ class.
<DataTemplate DataType='{x:Type Model:Thingy}'> <StackPanel Orientation='Horizontal'> <CheckBox x:Name='ThingyInListCheckBox' Click='ThingyInList_Click'></CheckBox> <TextBlock Text='{Binding Path=ThingyName}'></TextBlock> </StackPanel>
Here’s the XAML for the list boxes:
<ListBox Name='ListOfGroups' SelectionMode='Single'> </ListBox> <ListBox Name='ListOfThingys' SelectionMode='Single'> </ListBox>
I have the data binding for the list boxes set up in code, because I’m too tired to figure out how to do it in XAML:
ListOfGroups.ItemsSource = InMemoryCache.ThingyGroups; ListOfThingys.ItemsSource = InMemoryCache.Thingys;
What I want is the checkbox ‘ThingyInListCheckBox’ to be checked if the ‘thingy’ object is in the list that is the selected item in the ‘ListOfGroups’ listbox. So basically I need to bind it to the ‘Contains’ method of the ‘ListOfGroups’.SelectedItem while passing it the ‘ListOfThingys’.SelectedItem as a parameter.
I’m tempted to do this all in code, but I’m trying to get a better understanding of XAML data binding because I hate myself and I want me to suffer.
Is this even possible, or have I hit the inevitable ‘wall of databinding’ that exists in every other data binding system in the history of software development?
It is possible, in fact the hard thing is that there are many ways to do this and you have to choose one. None of them is a simple addition to your current code. However there is one way, by which you gain more than solving your problem. Actually, it is more of a pattern, called MVVM (some might argue about the naming).
Here is a small explanation on your example. Suppose ThingyGroup has an IsSelected property, which is bound to the IsSelected property of the containing ListBoxItem. Again, suppose Thingy has a Group property too. Then you can use Group.IsSelected as a path to bind checkbox. Notice that there is still a small issue that IsSelected is a bool and IsChecked is a nullable bool.
A search on MVVM should give you concrete samples.