I have a listbox that uses a datatemplate. What I need is a way after the item is selected I want to shrink the listbox itself, not the listitem inside. I have tried the eventtrigger on the selector.selected and unselected but it doesn't fire. I also put a datatrigger on the datatemplate but I cannot access the listbox from here. Any Ideas?
Wpf – Shrink ListBox on item selection
listboxlistboxitemwpf
Best Answer
This is a slightly indirect solution, but... you can handle this by putting a DataTrigger on the ListBox itself, and binding to the SelectedItems.Count. You will need to have the ListBox default to its "smaller" appearance. Then the trigger will check if SelectedItems.Count is 0, and if so it has to make the ListBox larger. In the following example, I'm setting the ListBox.Background for simplicity, but you should be able to adapt it to operate on the LayoutTransform or RenderTransform or Width/Height or whatever you're using to "shrink" the ListBox:
Obviously this will shrink (or, in my simplified example, turn white) the entire ListBox when anything is selected. To get the selected ListBoxItem to remain full sized, use the ListBox.ItemContainerStyle. In this, you can trigger on IsSelected, and apply a suitable setter to reverse the "shrinking" transformation -- e.g. apply a negative Margin, or the reverse ScaleTransform. (A normal Trigger will do for this.)