C# 为项目列表选择正确的控件

C# 为项目列表选择正确的控件,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我是WPF和MVVM的新手。在myViewModel中,我有项目集合,例如: class Item { string Title {get; set;} string Description {get; set;} } 我想创建一个视图,因此在开始时我会: Title1 Title2 Title3 如果用户单击其中一个标题,它将展开以显示说明,例如: Title1 Description1 Title2 Title3 如果用户单击其他标题,将有两个展开项: Title1 D

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

class Item {
    string Title {get; set;}
    string Description {get; set;}
}
我想创建一个视图,因此在开始时我会:

Title1
Title2
Title3
如果用户单击其中一个标题,它将展开以显示说明,例如:

Title1
Description1
Title2
Title3
如果用户单击其他标题,将有两个展开项:

Title1
Description1
Title2
Description2
Title3
这可能非常类似于
Expander
控件,也许我可以使用它,但我正在用另一种方式来学习新的东西

为此,我应该使用什么控件?应该是
ItemsControl
还是
ListBox

我想,如果我使用
ItemsControl
,我可能应该扩展我的
Item
类,使其具有类似
boolisexpanded
的内容,并将UI项可见性绑定到该值。但也许我可以使用
ListBox
并以某种方式将UI项可见性绑定到。。。是的,为了什么?:)


我怎么能做这么简单的事情呢?

除非您需要选择,否则您应该使用
ItemsControl
,为了实现扩展,您可以在
ItemsControl
DataTemplate
中定义此类行为,您只需创建一个轻量级扩展程序。其原理是使用
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>

我会用ListBox来处理这个问题,并在其中包含
ListBox.SelectionMode=“Multiple”

在ItemcontainerStyle上,您可以在列表框上有一个触发器。I选择使其展开。

您能告诉我如何将内容的可见性绑定到
切换按钮。I已按下
?它已被选中
,混淆了这一点;您可以使用
BooleanToVisibilityConverter
来执行此操作。