通过 DataTemplate 的分隔符
我有一个带有绑定 ItemsSource
的 ToolBar
,我使用 DataTemplateSelector
在运行时确定 DataTemplate
(即 <代码>按钮 / <代码>切换按钮)。
我想添加一个 Separator
DataTemplate
,我该怎么做?
I have a ToolBar
with a bound ItemsSource
, I am using DataTemplateSelector
to determine the DataTemplate
at runtime (i.e Button
/ ToggleButton
).
I want to add a Separator
DataTemplate
, how do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ToolBar 是一个 ItemsControl,因此它想用“容器”“包装” Items/ItemsSource 中定义的项目。容器是一个可用于显示项目的 UIElement。例如,对于 ListBox,容器是 ListBoxItem。如果一个项目是正确的类型,那么它也可以是它自己的容器。
此设置允许您将字符串列表传递到 ListBox 并让它显示属性并支持选择、键盘导航、样式等。
对于 ToolBar,它确实希望它的项目已经是一个容器(即 UIElement )。如果该项目不是 UIElement,那么它将用 ContentPresenter 包装它。
现在,容器使用 DataTemplateSelecter 来确定如何显示其项目。但是您需要该项目是 Button、ToggleButton、Separator 等。您建议您应该将容器添加到容器显示的 DataTemplate 中。
还有样式的问题,可以通过这个简单的示例看出:
顶部工具栏中的按钮将以与不在工具栏中相同的外观呈现。底部工具栏中的按钮将具有“工具栏”外观。分隔符也是如此。
您可以像这样手动应用样式:
使用分隔符也会遇到同样的问题。因此,您需要像这样手动应用样式:
您应该能够在 DataTemplateSelector 中使用上面的 DataTemplate,就像使用按钮一样。
The ToolBar is an ItemsControl, so it wants to "wrap" the items defined in Items/ItemsSource with a "container". The container is a UIElement that can be used to display the item. In the case of a ListBox for example, the container is a ListBoxItem. If an item is of the proper type, then it can also be it's own container.
This setup allows you to pass a list of strings to a ListBox and have it display property and support selection, keyboard navigation, styling, etc.
In the case of the ToolBar, it really expects it's items to already be a container (i.e. a UIElement). If the item is not a UIElement, then it will wrap it with a ContentPresenter.
Now, the DataTemplateSelecter is used by the container to determine how to display it's item. But you need the item to be a Button, ToggleButton, Separator, etc. You are suggesting that you should add the container in the DataTemplate displayed by the container.
There is also the problem of Styles, which can be seen with this simple example:
The buttons in the ToolBar on top will render with the same look as if they were not in the ToolBar. The buttons in the ToolBar on the bottom will get a "toolbar" look. The same goes for Separators.
You can manually apply the Style like so:
You would have the same problem with Separators. So you'd need to manually apply the Style like so:
You should be able to use the DataTemplate above in your DataTemplateSelector, just like you do with buttons.