[WPF/Silverlight] 項目を水平方向に並べる

スポンサーリンク

ListBox コントロールに表示する1つ1つの項目は ItemsPanel と呼ばれるレイアウトを制御するパネルで管理されています。

パネルの配置位置を変更したい場合は、ListBox コントロールの ControTemplateを作成します。このとき、ItemsPanelTemplate 要素内に StackPanel コントロールを置き、コントロールの配置方向を水平方向(Orientation属性をHorizontal)に設定します。

項目を水平方向に並べる例

XAMLの例

<ListBox Height="60" Margin="12,12,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="138">
    <ListBox.Template>
        <ControlTemplate TargetType="{x:Type ListBox}"><!-- ←WPFとSilverlightではここの記述が異なるので注意-->
        <!-- <ControlTemplate TargetType="ListBox"> --><!-- ←Silverlightはこっち-->
            <Border BorderBrush="#808080" BorderThickness="1" Margin="0">
                <ItemsPresenter Margin="5"/>
            </Border>
        </ControlTemplate>
    </ListBox.Template>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    
    <ListBoxItem Height="50">
        <StackPanel>
            <Image Height="20" Name="Japan" Source="./Images/japan.gif" Width="32" />
            <TextBlock>日本</TextBlock>
        </StackPanel>
    </ListBoxItem>
    <ListBoxItem Height="50">
        <StackPanel>
            <Image Height="20" Name="USA" Source="./Images/usa.gif" Width="32" />
            <TextBlock>アメリカ</TextBlock>
        </StackPanel>
    </ListBoxItem>
    <ListBoxItem Height="50">
        <StackPanel>
            <Image Height="20" Name="Canada" Source="./Images/canada.gif" Width="32" />
            <TextBlock>カナダ</TextBlock>
        </StackPanel>
    </ListBoxItem>
</ListBox>
タイトルとURLをコピーしました