为项目列表选择正确的控制

pro*_*ick 2 c# wpf xaml mvvm

我是WPF和MVVM的新手.在我ViewModel的项目集合中,例如:

class Item {
    string Title {get; set;}
    string Description {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个视图,所以在开始时我会:

Title1
Title2
Title3
Run Code Online (Sandbox Code Playgroud)

如果用户点击其中一个标题,它将展开以显示描述,例如:

Title1
Description1
Title2
Title3
Run Code Online (Sandbox Code Playgroud)

如果用户点击其他标题,则会有两个展开的项目:

Title1
Description1
Title2
Description2
Title3
Run Code Online (Sandbox Code Playgroud)

这可能非常类似于Expander控制,也许我可以使用它,但我正在以其他方式,以学习新的东西.

我应该为此目的使用什么控制?应该是ItemsControl或者可能ListBox吗?

我想,如果我使用ItemsControl,我应该扩展我的Item类,bool IsExpanded并将UI项可见性绑定到该值.但也许我可以使用ListBox并以某种方式将UI项目可见性绑定到...是的,对于什么?:)

我怎么能这么简单呢?

H.B*_*.B. 6

除非你需要选择你应该跟去ItemsControl,以达到扩展可以定义在这种行为DataTemplateItemsControl,你只需要创建一个轻量级的扩展.原则是ToggleButton将内容的可见性绑定到其IsChecked属性.

<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>
Run Code Online (Sandbox Code Playgroud)