星期三, 十二月 27, 2006

如何改变ItemsControl的布局

如何改变ItemsControl的布局


原文出处:http://www.beacosta.com/Archive/2005_10_01_bcosta_archive.html
在这个例子中,我将会介绍两个方法来改变ItemsControl的布局.为了回答我前面帖子的评论,这个例子使用XmlDataProvider,它可以绑定到XML数据.

改变ItemsControl布局的最简单的方法就是简单的设置ItemsPanel属性为你想要保存条目的Panel

    <ListBox ItemsSource="{Binding Source={StaticResource xmlData}}" (...) >
        <ListBox.ItemsPanel>
            <StackPanel Orientation="Horizontal" />
        </ListBox.ItemsPanel>
    </ListBox>

另外就是创建一个ControlTemplate,它允许被更广泛的定制.ControlTemplate允许你用替换掉整个VisualTree,包括选择一个新的Panel来保存条目.例如,下面的标记就显示了一个ControlTemplate,它增加一个了Border且改变了 ItemsControl的Panel.

    <ControlTemplate x:Key="listBoxTemplate">
        <Border BorderBrush="Orange" BorderThickness="2" Margin="10,0,10,10">
            <StackPanel Orientation="Horizontal" IsItemsHost="True" />
        </Border>
    </ControlTemplate>
    
    <ListBox ItemsSource="{Binding Source={StaticResource xmlData}}" Template="{StaticResource listBoxTemplate}" (...) />

Most people get this far in this scenario,但是忘记了设置Panel的IsItemsHost的属性.IsItemHost指明"使用这个Panel来放置 ItemsControl中的条目".注意,选择还是可以照常使用的.

如果你想让条目能够自动换行,你可以使用WrapPanel代替StackPanel.在这种情形下,要牢记ListBox的默认template包含一个ScrollViewer,因此你的条目是不会自动换行的.为了让它们换行你可以设置你自己的ControlTemplate,如果你不需要选择功能, 可以使用ItemsControl替代ListBox.

我前面提过,我使用XmlDataProvider绑定XML数据.这是我如何转化前面例子中使用的GreekGods运行时数据源:< br/>

    <Window.Resources>
        <XmlDataProvider XPath="/GreekGods/GreekGod" x:Key="xmlData">
            <GreekGods xmlns="">
                <GreekGod>
                    <Name>Aphrodite</Name>
                    <Description>Goddess of love, beauty and fertility</Description>
                    <RomanName>Venus</RomanName>
                </GreekGod>
                (...)
            </GreekGods>
        </XmlDataProvider>
    </Window.Resources>

你只需要记住在绑定对象中使用XPath属性代替Path属性.使用DisplayMemberPath格式时,Path和XPath都可以使用.

没有评论: