问题与WPF衍生CONTROLTEMPLATES

问题描述:

下面的XAML代码工作:问题与WPF衍生CONTROLTEMPLATES

<Window x:Class="DerivedTemplateBug.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:DerivedTemplateBug" 
Title="Window1" Height="300" Width="300"> 
<Button> 
    <Button.Template> 
    <ControlTemplate> 
    <Border BorderBrush="Black" BorderThickness="2"> 
    <TextBlock>Testing!</TextBlock> 
    </Border> 
    </ControlTemplate> 
    </Button.Template> 
</Button> 
</Window> 

现在,如果你定义了以下数据模板:

using System.Windows.Controls; 

namespace DerivedTemplateBug 
{ 
public class DerivedTemplate : ControlTemplate 
{ 
} 
} 

然后交换的ControlTemplate派生类:

<Window x:Class="DerivedTemplateBug.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:DerivedTemplateBug" 
Title="Window1" Height="300" Width="300"> 
<Button> 
    <Button.Template> 
    <local:DerivedTemplate> 
    <Border BorderBrush="Black" BorderThickness="2"> 
    <TextBlock>Testing!</TextBlock> 
    </Border> 
    </local:DerivedTemplate> 
    </Button.Template> 
</Button> 
</Window> 

您收到以下错误信息:

找不到类型为'DerivedTemplateBug.DerivedTemplate'的属性'Content'的ContentPropertyAttribute无效。

谁能告诉我为什么这样?

+0

嗯,我没有看到您所看到的错误? Derived模板中是否还有其他可能隐藏基础ControlTemplate.Content属性的内容?出于好奇,也是这个.NET 3.5或4.0。 – 2010-03-11 19:05:07

+0

我使用.net 3.5和Visual Studio Professional 2008。这里发布的代码是从我创建的干净解决方案逐字复制的。 – Farnk 2010-03-11 20:56:54

我得到一个不同的错误,当我试试这个:

'Border' object cannot be added to 'DerivedTemplate'. 
Object of type 'System.Windows.Controls.Border' cannot be converted 
to type 'System.Windows.FrameworkElementFactory'. 

仰望FrameworkElementFactory,看来这是在代码中创建模板的老办法:

This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class.

我的问题是,为什么你是从ControlTemplate继承吗?我无法想到这样做的用例。如果您只是试图在代码隐藏方面创建自己的模板,MSDN建议采用以下方法:

The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.

+0

我们的项目在运行时加载xaml文件以创建动态用户可编辑UI。我们需要有关模板的其他数据,以了解它应该用于什么以及其他事情。 你得到的错误实际上是我在我的测试项目中遇到这个错误时试图调试的错误。 我认为你得到的错误是xaml编译器中的一个错误。 ControlTemplate的'ContentProperty'是类型为FrameworkElementFactory的VisualTree属性。当您使用DataTemplate或ControlTemplate时,它会自动将xaml转换为元素,但是当您继承它时则不会。 – Farnk 2010-03-12 14:13:03

+0

你能尝试解决这个使用组合?换句话说,不是从ControlTemplate继承,而是创建一个包含ControlTemplate的单独类,以及所需的所有其他数据。然后传递该类而不是ControlTemplate。在我看来,这个解决方案似乎是一个更好的方法。 – Charlie 2010-03-14 22:03:57

+0

我认为作文可能是答案,我们将尝试。谢谢! – Farnk 2010-04-06 12:41:32