将StackPanel用作ContentControl(WPF)

5
我有一个StackPanel,它被我用作ContentControl。我有一个地方需要根据我绑定的数据生成按钮,这一切都很顺利,但我希望按钮水平排列,而不是垂直排列,目前的情况正是这样。以下是屏幕截图: alt text 这是我的ContentTemplate描述中的代码:
<StackPanel Name="wpReleaseButtons" Orientation="Horizontal" Grid.Row="2">
    <ItemsControl IsTabStop="False" ItemsSource="{Binding Path=BranchCommands}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Tag="{Binding}" Padding="3">
                     <TextBlock Text="{Binding Path=DisplayValue}" />
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>

我不确定我在这里做错了什么。希望能得到任何信息,非常感谢。

2个回答

9

我认为这个ItemsControl是以垂直方式显示按钮的。如果你想让ItemsControl中的按钮水平排列,则需要将StackPanel放在ItemsControlItemsPanelTemplate中,而不是像你代码中所写的那样。

<ItemsControl IsTabStop="False" ItemsSource="{Binding Path=BranchCommands}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Tag="{Binding}" Padding="3">
                <TextBlock Text="{Binding Path=DisplayValue}" />
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

我可能在ItemsControl.ItemsPanel 的部分有些错误,因为我没有任何数据进行测试...

编辑:除了 Bea 参考之外,还有一些好的内容来自 Dr WPF


这就做到了!!!感谢您的答案,我也已经收藏了Bea的网站。谢谢大家!这个问题开始让我相当困扰,哈哈。 - James McConnell

3
我看不到你的图片(被我的公司防火墙屏蔽了),但是我还是要说一下...

你的 'Orientation="Horizontal"' 可能已经按照预期工作:它只包含一个子元素,即 ItemsControl。相反,尝试为 ItemsControl 制作 ControlTemplate,其中 ControlTemplate 包含一个 Orientation="Horizontal" 的 StackPanel。

希望这有所帮助!

编辑:

再一次,Bea 提供了一个答案/示例!

http://bea.stollnitz.com/blog/?p=10


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接