Using StackPanel as ContentControl (WPF)

北战南征 提交于 2019-12-07 05:07:59

问题


So I have a StackPanel that I am using as a ContentControl. I have a place where I want buttons to be generated based on data that I am binding to, and that is all working good, but I want the buttons to be laid out horizontally, not vertically as is what is currently happening. Here's a screenshot:

And here is the code from my ContentTemplate description:

<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>

Not sure what I'm doing wrong here. Any info would be greatly appreciated. Thanks!


回答1:


I would say it looks like the ItemsControl is what is displaying the buttons vertically. if you want the buttons in the ItemsControl to be horizontal, then you need the StackPanel to be in the ItemsControl ItemsPanelTemplate, not the other way round like what you have in your code:

<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>

I might be slightly wrong on the ItemsControl.ItemsPanel bit as I haven't got any data to test it with...

Edit: In addition to the Bea reference, there's some good stuff by Dr WPF.




回答2:


I can't see your image (it's blocked by my company's firewall), but here I go anyways...

Your 'Orientation="Horizontal"' is probably working as it should: it only contains one child element, an ItemsControl. Instead, try making a ControlTemplate for your ItemsControl, where the ControlTemplate contains a StackPanel with Orientation="Horizontal".

Hope this helps!

Edit:

Once again, Bea comes through with an answer/example!

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



来源:https://stackoverflow.com/questions/934873/using-stackpanel-as-contentcontrol-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!