I have a scenario where I have a globally available Properties window (similar to the Properties window in Visual Studio), which is bound to a SelectedObject property of my model. I have a number of different ways to browse and select objects, so my first attempt was to bind them to SelectedObject directly. For example:
<ListBox ItemsSource="{Binding ActiveProject.Controllers}"
SelectedItem="{Binding SelectedObject, Mode=TwoWay}"/>
<ListBox ItemsSource="{Binding ActiveProject.Machines}"
SelectedItem="{Binding SelectedObject, Mode=TwoWay}"/>
This works well when I have more than one item in each list, but it fails if a list has only one item. When I select the item, SelectedObject is not updated, since the list still thinks its original item was selected. I believe this happens because the two way binding simply ignores the update from source when SelectedObject is not an object in the list, leaving the list's SelectedItem unchanged. In this way, the bindings become out of sync.
Does anybody know of a way to make sure the list boxes reset their SelectedItem when the SelectedObject is not in the list? Is there a better way to do this that doesn't suffer from this problem?