【问题标题】:How Can You Bind a List<String> to a StackPanel [closed]如何将 List<String> 绑定到 StackPanel [关闭]
【发布时间】:2013-08-13 19:28:26
【问题描述】:

在我的应用程序中,我有一个strings 的List,但是我不知道如何/不知道如何将此列表绑定到StackPanel

我尝试使用ListBox,但ListBox 的滚动特性对我的应用程序的用户来说非常不方便。

那么有谁知道我如何将strings 的List 绑定到StackPanel

我尝试弄乱了几个属性,但没有找到任何东西。

感谢您的帮助!

【问题讨论】:

  • 你试过什么?我很确定互联网上有很多例子。请做一些研究并表现出努力,而不是期望别人给你答案或做你的工作谢谢

标签: c# list windows-phone-7 binding windows-phone-8


【解决方案1】:

要将枚举绑定到控件并显示它们,您可以使用任何ItemsControl 并将您的对象绑定到ItemsSource 属性。 ItemsControls 公开了一个名为 ItemsPanel 的属性,您可以在其中进一步修改以更改项目的容器。 StackPanel 是其中大多数的默认值。

<ItemsControl ItemsSource="{Binding NewbieList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <!-- The default for an ItemsControl is a StackPanel with a vertical orientation -->
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

编辑:

至于您的评论,ItemsSource 中的任何内容都将“输出”ItemTemplate 属性中的内容(默认基本上是 TextBlock,文本绑定到 DataContext)。对于每个元素,DataContext 将是列表中的项目。例如,如果你有一个string 的列表,你可以这样做:

<!-- Rest is omitted for succinctness -->
<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding .}" FontSize="26" MouseDown="yourEventHandler"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
<ItemsControl>

或者,如果您只想更改字体大小,您可以使用ItemsControl 本身的TextElement.FontSize 依赖属性或设置ItemsContainer 的样式:

<ItemsControl TextElement.FontSize="26">
    <!-- Rest omitted for succinctness -->
</ItemsControl>

或者:

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="TextElement.FontSize" Value="26"/>
    </Style>
</ItemsControl.ItemContainerStyle>

我建议您阅读有关 WPF 中的绑定和项目控制的文章/教程,以了解有关如何执行各种任务的更多信息,有很多要解释的。

【讨论】:

  • 这几乎可以工作,但我需要能够为模板中的每个单独项目检索点击事件,而我似乎无法使用 StackPanel 做到这一点
  • @Newbie 查看我的编辑。您绝对应该阅读有关 WPF 的一些教程,以获取有关绑定、数据模板和项目控制的更多信息。
  • 是的,我尝试只使用TextBlock,但这引发了 UnhandledException,抱歉,您费尽心思回答我已删除的评论,我只是在下方添加 FontSize="32" 就知道了Items.Control.
猜你喜欢
  • 2011-02-10
  • 2021-06-28
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多