【问题标题】:Choosing right control for list of items为项目列表选择正确的控件
【发布时间】:2011-01-31 20:28:58
【问题描述】:

我是 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 项可见性绑定到...是的,绑定到什么? :)

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

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    除非你需要选择你应该使用ItemsControl,为了实现扩展你可以在ItemsControlDataTemplate中定义这样的行为,你只需要创建一个轻量级的扩展器。原理是要有一个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>
    

    【讨论】:

    • 你能告诉我如何将内容的可见性绑定到ToggleButton.IsPressed吗?
    • IsChecked,搞混了;你可以使用BooleanToVisibilityConverter 来做到这一点。
    【解决方案2】:

    我会使用 ListBox 来解决这个问题,并在其中包含 ListBox.SelectionMode="Multiple"。 在 ItemcontainerStyle 上,您可以在 ListBox.IsSelected 上设置一个触发器以使其展开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 2011-05-29
      • 1970-01-01
      相关资源
      最近更新 更多