1

如果我有一个派生自System.Windows.DispatcherObject但定义了ControlTemplate.

public class A : System.Windows.DependencyObject
{
   public ControlTemplate ControlTemplate {get; set;}
}

它是

public class B 
{
   public A NonUIElement {get; set;}
}

是否可以通过 Binding 渲染此对象,例如

<Border Name="Border">
<ContentPresenter Margin="5,0" Content="{Binding NonUIElement }"/>
</Border>

假设DataContext边框设置为 B 的实例?

4

2 回答 2

3

该对象将呈现,但不会以我认为您希望的方式呈现。 The ContentofContentPresenter设置为 A 的实例。然后 WPF 试图弄清楚如何渲染 A 的这个实例。它首先问,这个对象是 aUIElement吗?在这种情况下,答案是否定的。所以它接下来会寻找一个DataTemplate类型。在这种情况下,没有DataTemplateA 类。所以它依赖于调用 ToString()。因此,您ContentPresenter将显示一个TextBlock包含文本“YourNamespace.A”的内容。

A 碰巧有一个 type 成员的ControlTemplate事实不会影响这个逻辑。对于 WPF,这只是 A 恰好携带的一大块数据。WPF 仅在涉及控件并且分配给属性时使用。 ControlTemplateControlTemplateTemplate

因此,您需要DataTemplate为 A 提供一个(它当然可以访问ControlTemplate并使用它来呈现实例),或者创建一个命名DataTemplate并应用它 via ContentPresenter.ContentTemplate,或者派生自UIElement

于 2009-12-18T20:52:09.233 回答
0

我终于明白了;

<HierarchicalDataTemplate DataType="{x:Type vm:MapLayerModel}" ItemsSource="{Binding Path=Children, Mode=OneTime}">   
**<ContentControl Margin="5" Content="{Binding LayerRepresentation}" Template="{Binding LayerRepresentation.ControlTemplate}" Mode=OneTime/>**
</HierarchicalDataTemplate>

这是关于 WPF 模板及其内容控制模型的精彩个人课程。再次感谢伊托尔森。

于 2009-12-20T05:19:14.750 回答