wpf 将数据模板传递给新 window
wpf pass datatemplate to new window
我需要将 DataTemplate 发送到新的 window 以进行打印。
1) 我创建了一个通用的 Window 让我们将其命名为 PrintPreview 包含以下内容:
FlowDocument > BlockUiContainer > ContentControl (负责显示我要发送的DataTemplate到它)
问题是数据模板内的绑定不起作用。 (并非适用于所有情况)
例如:
我的应用程序中某处有这个数据模板
<DataTemplate x:Key="MyPrintPreview">
<DockPanel>
<TextBlock Text="{Binding SomeProperty1,RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBlock>
<TextBlock Text="{Binding Source={StaticResource SomeViewModel},Path=SomeProperty2}"></TextBlock>
</DockPanel>
</DataTemplate>
上面的 DataTemplate 运行良好,并在我当前的视图 (UserControl) 中显示了这两个属性
但是当我将此 DataTemplate 发送到新的 Window PrintPreview 时,我遇到了以下问题
第一个 TextBlock (SomeProperty1) 显示内容失败
第二个 TextBlock (SomeProperty2) 显示得很好!
我不知道该怎么做。或者如果我做错了?
您应该将 ContentControl
的 Content
属性 设置或绑定到包含 ContentTemplate
中的元素尝试绑定到的属性的对象。
所以将ContentControl
的ContentTemplate
属性设置为你的DataTemplate
并将Content
属性设置为实际对象绑定到。这就是应该使用 ContentControl
的方式。
另请注意,要使您的第一个绑定生效,ContentControl
必须是 UserControl
的子级,因为您要绑定到父级 UserControl
的 SomeProperty1
.如果没有父级 UserControl
,绑定将始终失败。
我需要将 DataTemplate 发送到新的 window 以进行打印。
1) 我创建了一个通用的 Window 让我们将其命名为 PrintPreview 包含以下内容:
FlowDocument > BlockUiContainer > ContentControl (负责显示我要发送的DataTemplate到它)
问题是数据模板内的绑定不起作用。 (并非适用于所有情况)
例如: 我的应用程序中某处有这个数据模板
<DataTemplate x:Key="MyPrintPreview">
<DockPanel>
<TextBlock Text="{Binding SomeProperty1,RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBlock>
<TextBlock Text="{Binding Source={StaticResource SomeViewModel},Path=SomeProperty2}"></TextBlock>
</DockPanel>
</DataTemplate>
上面的 DataTemplate 运行良好,并在我当前的视图 (UserControl) 中显示了这两个属性 但是当我将此 DataTemplate 发送到新的 Window PrintPreview 时,我遇到了以下问题
第一个 TextBlock (SomeProperty1) 显示内容失败
第二个 TextBlock (SomeProperty2) 显示得很好!
我不知道该怎么做。或者如果我做错了?
您应该将 ContentControl
的 Content
属性 设置或绑定到包含 ContentTemplate
中的元素尝试绑定到的属性的对象。
所以将ContentControl
的ContentTemplate
属性设置为你的DataTemplate
并将Content
属性设置为实际对象绑定到。这就是应该使用 ContentControl
的方式。
另请注意,要使您的第一个绑定生效,ContentControl
必须是 UserControl
的子级,因为您要绑定到父级 UserControl
的 SomeProperty1
.如果没有父级 UserControl
,绑定将始终失败。