【发布时间】:2011-03-04 18:02:30
【问题描述】:
作为ItemsControl 风格的一部分,我希望拥有与Grid/UniformGrid 类似的东西ItemsPanel。
Style 最简单的形式如下所示:
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ItemsPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<UniformGrid Columns="2" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style>
<Setter Property="Control.Margin" Value="10"/>
</Style>
</Setter.Value>
</Setter>
</Style>
我会这样使用它:
<WrapPanel Orientation="Vertical">
<ItemsControl>
<TextBlock Text="Label1:"/>
<TextBlock Text="ThisWillBeBound" />
</ItemsControl>
<ItemsControl>
<TextBlock Text="Label2:"/>
<TextBlock Text="ThisWillBeBound" />
</ItemsControl>
<ItemsControl>
<TextBlock Text="Label3:"/>
<TextBlock Text="ThisWillBeBound" />
</ItemsControl>
<ItemsControl>
<TextBlock Text="Label4:"/>
<TextBlock Text="ThisWillBeBoundButIsSomewhatLongerThenTheOtherProperties" />
</ItemsControl>
<ItemsControl>
<TextBlock Text="Label5:"/>
<TextBlock Text="ThisWillBeBound" />
</ItemsControl>
<ItemsControl>
<TextBlock Text="Label6:"/>
<TextBlock Text="ThisWillBeBound" />
</ItemsControl>
</WrapPanel>
如您所见,您可以将属性的 Label 扔到 this 中,并绑定到该属性,它们会粘在一起,即使由于应用程序窗口的大小不同而发生环绕,它们也会粘在一起。
关于UniformGrid 的好处是,如果一个Label 更长,其他人将获得相同的空间,这意味着绑定的属性将整齐排列(为什么会发生这种情况我不明白,因为这些我猜应该是单独的UniformGrids)。这里的问题是Label部分和Property部分的单元格宽度相同,所以如果属性很长,Label和Property之间会有很大的差距。
改用普通的Grid 意味着我必须在我将项目放入ItemsControl 的每个地方都设置Grid.Column="0" 和Grid.Column="1"。这不是我真正想要的。
我有没有办法让某种网格像统一的网格一样排列,但在只需要一个网格时不会对所有列进行分层,并假设您以与声明项目相同的方式放入列?
【问题讨论】:
标签: wpf user-interface xaml styles itemscontrol