繁体   English   中英

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

[英]Choosing right control for list of items

我是WPF和MVVM的新手。 在我的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类,使其具有bool IsExpanded类的东西,并将UI项目可见性绑定到该值。 但是也许我可以使用ListBox并以某种方式将UI项可见性绑定到...是的,是什么? :)

我该怎么做这么简单的事情?

除非需要选择,否则应该使用ItemsControl来实现扩展,您可以在ItemsControlDataTemplate中定义这种行为,只需创建一个轻量级的Expander。 原理是要有一个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上,可以在ListBox.IsSelected上具有一个触发器以使其展开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM