我想为我的窗口创建一个用户控件,用于定义某些样式等,并且该控件将具有几个插槽,用于插入内容 - 例如,模态对话框窗口的模板将具有内容和按钮插槽(因此用户可以提供内容和一组绑定ICommand的按钮)。
我希望像这样拥有一个控件(但这不起作用):
UserControl 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),但是再次强调:Window只有一个内容插槽,因此它的模板只能有一个presenter,但我需要两个(即使在这种情况下,可能只需要一个,但还有其他用例需要多个内容插槽,比如文章模板-控件用户会提供标题,结构化内容,作者姓名,图像等)。
谢谢!
PS:如果我想将多个控件(按钮)并排放置,如何将它们放入 StackPanel 中?ListBox 有 ItemsSource,但 StackPanel 没有,并且其 Children 属性是只读的-因此这种方法无法实现(在 usercontrol 内部):
<StackPanel
Orientation="Horizontal"
Children="{Binding Buttons}"/>
编辑:我不想使用绑定,因为我想将一个DataContext(ViewModel)分配给整个窗口(相当于View),然后从插入到控件“插槽”中的按钮绑定到它的命令——因此,在层次结构中使用任何绑定都会破坏View的DC的继承。
至于从HeaderedContentControl继承的想法-是的,在这种情况下它会起作用,但是如果我想要三个可替换部分怎么办?如何制作自己的“HeaderedAndFooteredContentControl”(或者如果我没有一个HeaderedContentControl该怎么实现)?
编辑2:好的,我的两个解决方案都不起作用-原因如下: ContentPresenter从DataContext获取其内容,但我需要所包含元素的绑定链接到原始窗口(UserControl在逻辑树中的父级上)的DataContext-因为这样,当我嵌入绑定到ViewModel属性的文本框时,它不会被绑定,由于继承链已经在控件内部断开了!
似乎我需要保存父级的DataContext,并将其恢复到所有控件容器的子级,但我没有得到任何有关逻辑树中DataContext已更改的事件。
编辑3:我有了一个解决方案!删除了我的先前回答。 请参阅我的响应。