【发布时间】:2010-11-05 00:32:58
【问题描述】:
我正在开发 LOB 应用程序,我需要多个对话框窗口(在一个窗口中显示所有内容不是一种选择/没有意义)。
我希望我的窗口有一个用户控件,它可以定义一些样式等,并且会有 几个 可以插入内容的插槽 - 例如,模态对话框窗口的模板将有一个内容槽和按钮槽(这样用户就可以提供一个内容和一组带有绑定 ICommand 的按钮)。
我想要这样的东西(但这不起作用):
用户控件 xaml:
<UserControl x:Class="TkMVVMContainersSample.Services.Common.GUI.DialogControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
>
<DockPanel>
<DockPanel
LastChildFill="False"
HorizontalAlignment="Stretch"
DockPanel.Dock="Bottom">
<ContentPresenter ContentSource="{Binding Buttons}"/>
</DockPanel>
<Border
Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
Padding="8"
>
<ContentPresenter ContentSource="{Binding Controls}"/>
</Border>
</DockPanel>
</UserControl>
这样的事情可能吗?我应该如何告诉 VS 我的控件公开了两个内容占位符,以便我可以这样使用它?
<Window ... DataContext="MyViewModel">
<gui:DialogControl>
<gui:DialogControl.Controls>
<!-- My dialog content - grid with textboxes etc...
inherits the Window's DC - DialogControl just passes it through -->
</gui:DialogControl.Controls>
<gui:DialogControl.Buttons>
<!-- My dialog's buttons with wiring, like
<Button Command="{Binding HelpCommand}">Help</Button>
<Button Command="{Binding CancelCommand}">Cancel</Button>
<Button Command="{Binding OKCommand}">OK</Button>
- they inherit DC from the Window, so the OKCommand binds to MyViewModel.OKCommand
-->
</gui:DialogControl.Buttons>
</gui:DialogControl>
</Window>
或者也许我可以为窗口 like here 使用 ControlTemplate,但话又说回来:窗口只有一个内容槽,因此它的模板只能有一个演示者,但我需要两个(如果在这种情况下它可能会与一个一起使用,还有其他用例会出现多个内容槽,只需考虑文章的模板 - 控件的用户将提供标题、(结构化)内容、作者姓名、图像...... )。
谢谢!
PS:如果我只想并排放置按钮,如何将多个控件(按钮)放到 StackPanel 中? ListBox 有 ItemsSource,但 StackPanel 没有,而且它的 Children 属性是只读的 - 所以这不起作用(在用户控件内部):
<StackPanel
Orientation="Horizontal"
Children="{Binding Buttons}"/>
编辑:我不想使用绑定,因为我想将 DataContext (ViewModel) 分配给整个窗口(等于 View),然后从插入到控件“插槽”中的按钮绑定到它的命令 - 所以在层次结构中使用任何绑定都会破坏 View 的 DC 的继承。
至于从 HeaderedContentControl 继承的想法——是的,在这种情况下它会起作用,但是如果我想要三个可替换的部分呢?我如何制作自己的“HeaderedAndFooteredContentControl”(或者,如果我没有 HeaderedContentControl,我将如何实现)?
EDIT2:好的,所以我的两个解决方案不起作用 - 这就是原因: ContentPresenter 从 DataContext 获取它的内容,但我需要对包含的元素进行绑定以链接到原始窗口(逻辑树中 UserControl 的父级)DataContext - 因为这样,当我嵌入绑定到 ViewModel 属性的文本框时,它没有被绑定,因为控件内部的继承链被破坏了!
似乎我需要保存父级的 DataContext,并将其恢复到所有控件容器的子级,但我没有收到任何事件表明逻辑树中的 DataContext 已更改。
EDIT3:我有一个解决方案!,删除了我之前的回答。 请参阅我的回复。
【问题讨论】:
标签: wpf user-controls contentpresenter