Choosing right control for list of items
I am new to WPF and MVVM. In my ViewModel
I have collection of items, for example:
class Item {
string Title {get; set;}
string Description {get; set;}
}
I would like to create a view, so at the beginning I would have:
Title1
Title2
Title3
If user click on one of title it will expand to show description, eg:
Title1
Description1
Title2
Title3
If user click on other title, there will be two expanded items:
Title1
Description1
Title2
Description2
Title3
This is probably very similar to Expander
control and maybe I could use it, but I am doing it other way, to learn something new.
开发者_开发百科What control should I use for this purpose? Should that be ItemsControl
or maybe ListBox
?
I imagine, that if I use ItemsControl
, I should probably extend my Item
class to have something like bool IsExpanded
and bind UI item visibility to that value. But maybe I could use ListBox
and somehow bind UI item visibility to... Yeah, to what? :)
How could I do such a simple thing?
Unless you need selection you should go with the ItemsControl
, to achieve the expansion you can define such behaviour in the DataTemplate
of the ItemsControl
, you'd just create a lightweight Expander. The principle is to have a ToggleButton
and bind the visibility of the content to its IsChecked
property.
<ItemsControl ItemsSource="{Binding Data}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<BooleanToVisibilityConverter x:Key="B2VConv"/>
</DataTemplate.Resources>
<StackPanel Orientation="Vertical">
<ToggleButton x:Name="tbutton" Content="{Binding Title}">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<ContentPresenter/>
</ControlTemplate>
</ToggleButton.Template>
<ToggleButton.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ToggleButton.ContentTemplate>
</ToggleButton>
<TextBlock Text="{Binding Description}"
Visibility="{Binding ElementName=tbutton, Path=IsChecked,Converter={StaticResource B2VConv}}">
</TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I would approach this with ListBox and have ListBox.SelectionMode="Multiple"
in it.
On the ItemcontainerStyle you can have a Trigger on the ListBox.IsSelected to make it expanded.
精彩评论