我正在使用一个自定义窗口类,它向窗口添加了一些行为:
class CustomWindow : Window {
public CustomWindow() {
// ...
}
}
我当前的MainWindow.xaml
看起来像预期的那样:
<local:CustomWindow ...>
<!-- ... -->
</local:CustomWindow>
现在我想在一个自定义容器中托管窗口的内容,该容器应该是窗口本身的根元素,但我一开始就努力实现容器的自动创建。因此,我正在使用“硬编码”控件手动执行我想要自动化的内容:
<local:CustomWindow ...>
<local:CustomUserControl>
<!-- ... -->
</local:CustomUserControl>
</local:CustomWindow>
为了显示通过XAML添加的内容,我引入了一个Content属性,如下所示:
[ContentProperty("InnerContent")]
public partial class CustomUserControl : UserControl
{
public static readonly DependencyProperty InnerContentProperty =
DependencyProperty.Register("InnerContent", typeof(object),
typeof(CustomUserControl));
public object InnerContent
{
get => GetValue(InnerContentProperty);
set => SetValue(InnerContentProperty, value);
}
}
带有ContentPresenter
的XAML文件中的Content="{Binding Path=InnerContent, ElementName=customUserControl}"
。在这一点上,我正在努力进行一些我想要实现的进一步绑定。我有一个TextBlock,我想绑定到父窗口的属性。层次结构如下所示:
CustomWindow
|- CustomUserControl
|- ...
|- TextBlock
当我将Text
属性设置为{Binding Path=Title, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomWindow}}}
时,这在运行时期间有效,但在窗口设计器的设计时间内无效。当然,我不能将这个绑定与我引入的设计DataContext
一起使用d:DataContext="{d:DesignInstance local:FakeCustomUserControlData, IsDesignTimeCreatable=True}"
。
此时我有两个问题:
CustomUserControl.xaml
设计器中设置设计时数据,而在MainWindow.xaml
设计器中,在运行时我获得有关父项的真实数据? (我在测试期间注意到Parent
的{{1}}属性在其构造函数中为null,因此如果存在父窗口,我无法获取父窗口的数据。)CustomUserControl
“注入”窗口而无需手动将其添加到窗口中?我试图替换CustomUserControl
构造函数中的Content
属性,但它在某些时候被替换,并且永远不可见。答案 0 :(得分:1)
实际上是否有办法将
CustomUserControl
“注入”窗口而无需手动将其添加到窗口中?
为包含UserControl
:
<Window x:Class="WpfApp1.Window1"
...>
<Window.Template>
<ControlTemplate TargetType="Window">
<AdornerDecorator>
<local:CustomUserControl Background="White">
<ContentPresenter />
</local:CustomUserControl>
</AdornerDecorator>
</ControlTemplate>
</Window.Template>
<Grid>
<TextBlock>the content...</TextBlock>
</Grid>
</Window>
是否可以在CustomUserControl.xaml设计器中拥有设计时数据,而在
MainWindow.xaml
设计器中,在运行时我获得有关父级的真实数据?
您应该能够为UserControl
:WPF data context for design time and run time设置设计时数据上下文。