目标:
我试图在 WPF 中实现这样的目标:
(来源:wordpress.org)
初始解决方案:
目前,我正在尝试使用 ItemsControl
与 ItemTemplate
由 Expander
组成.
我想要 Header
的一致外观Expander
的一部分,但我想要 Content
Expander
的一部分完全灵活。因此,它基本上是一组垂直堆叠的“portlet”,其中每个 portlet 都有一致的标题栏但内容不同。
到目前为止的代码:
这就是我目前所拥有的:
<ItemsControl
Grid.Row="2"
Grid.Column="2">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander>
<Expander.HeaderTemplate>
<DataTemplate>
<StackPanel
Orientation="Horizontal">
<TextBlock
FontSize="14"
FontWeight="Bold"
Text="Title_Of_Expander_Goes_Here" />
<TextBlock
Margin="10,0,0,0"
FontWeight="Bold"
FontSize="18"
Text="*" />
</StackPanel>
</DataTemplate>
</Expander.HeaderTemplate>
<Expander.Template>
<ControlTemplate
TargetType="Expander">
<Border
BorderThickness="1">
<ContentPresenter />
</Border>
</ControlTemplate>
</Expander.Template>
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.Items>
<StackPanel>
<TextBlock
FontSize="14"
FontWeight="Bold"
Text="Users:" />
<wt:DataGrid
Margin="0,1,0,0"
AutoGenerateColumns="False"
CanUserAddRows="True"
CanUserDeleteRows="True"
ItemsSource="{Binding Source={StaticResource Main_SystemUsers}, XPath=//Users/*}">
<wt:DataGrid.Columns>
<wt:DataGridTextColumn
Header="User Name"
Binding="{Binding XPath=@UserName}" />
<wt:DataGridComboBoxColumn
Header="Role"
ItemsSource="{Binding Source={StaticResource Main_UserRoles}, XPath=//Roles/*}"
SelectedValueBinding="{Binding XPath=@Role}" />
</wt:DataGrid.Columns>
</wt:DataGrid>
<StackPanel
Margin="0,10,0,0"
Orientation="Horizontal">
<Button
Content="Add New User..." />
<Button
Margin="10,0,0,0"
Content="Delete User..." />
</StackPanel>
</StackPanel>
</ItemsControl.Items>
</ItemsControl>
讨论:
当我运行它时唯一出现的是
DataGrid
用户及其下方的按钮(“添加新用户”和“删除用户”)。没有Expander
或标题栏。另外,即使我确实看到了,我也不知道如何设置 Binding
对于出现在标题栏上的标题。如果我使用 ItemsSource
,我知道如何进行绑定(bind),但我想以声明方式设置我的项目。问题:
我该怎么办?我正在寻找我现在拥有的解决方案或干净的解决方案。
编辑:
我最终做的是替换
ItemsControl
与 StackPanel
并且只是为我的扩展器写一个样式。事实证明这要简单得多,而且 ItemsControl
确实没有任何好处。因为无论如何我都需要为每个项目声明自定义内容。剩下的一个问题是如何为每个扩展器实现自定义标题。这就是@Thomas Levesque 建议使用 TemplateBinding
的地方进来了。我所要做的就是替换Text="Title_Of_Expander_Goes_Here"
在我的 header 模板(参见上面的代码)中使用 Text="{TemplateBinding Content}"
.
最佳答案
您没有看到 Expander,因为您重新定义了它的模板。这个应该更好用:
...
<Expander.Template>
<ControlTemplate
TargetType="Expander">
<Border
BorderThickness="1">
<Expander Content="{TemplateBinding Content}" Header="{TemplateBinding Header}"/>
</Border>
</ControlTemplate>
</Expander.Template>
...
关于wpf - 如何在 WPF 中创建 "Accordion Widget"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1474838/