One of my clients requests the ability to "autoexpand" listbox items on item's selection. He showed me his code for it. You know... A lot of code-behind, that detects all unselected items and collapse them. Bad, very bad way.
I told him, that all this code (about 200 lines), I'll rewrite in WPF within a half line of the code. He agreed to challenge for 200 NIS, after seeing WPF books...
The first thing I need is to create DataSource. Really simple, only for presentation. Next step, is to connect datasource to listbox. Simple as well.
<XmlDataProvider x:Key="myData" XPath="Items/Item"/>
<ListBox IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource myData}}"/>
Next, we need a data template:
<Expander Header="{Binding XPath=Title}" Width="300">
<TextBlock TextWrapping="Wrap" Text="{Binding XPath=Article}"/>
</Expander>
Piece of cake, no? And now, the magic half-line, that worth 50$ :). Expander has IsExpanded dependency property. The ListBoxItem has IsSelected dependency property. Let's connect them. But how? While creating DataTemplate for ListBoxItem, the WPF creates "virtual" item for us, so the Expander becomes ListBoxItem and we have to take it's DP. We'll ask him to find ancestor from underlying type, named ListBoxItem and go to IsSelected property. Isn't is clear as shine?
IsExpanded="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}},Path=IsSelected}"
That's all folks. Now each Expander inside ListBox will be Expanded if the underlying data item is Selected, else, it'll be collapsed.
The additional way to do the same thing is by using Styles and data triggers, but it's already more then a half line of code. Too bad :)
See yourself
1) DataTriggers (5 lines)
<DataTemplate x:Key="myItem">
<Expander Name="exp" Header="{Binding XPath=Title}" Width="300">
<TextBlock TextWrapping="Wrap" Text="{Binding XPath=Article}"/>
</Expander>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1}, Path=IsSelected}" Value="True">
<Setter Property="IsExpanded" Value="True" TargetName="exp" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
2) Styles (7 lines)
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Expander.IsExpanded" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
Thank you WPF. (The source code for this article)
No comments:
Post a Comment