我正在开发 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>
或者,也许我可以将 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:我有一个解决方案!,删除了我之前的回答。看我的回复。