下面的xaml代码可以工作:
<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‘的内容无效,找不到属性’ContentPropertyAttribute‘。
有人能告诉我为什么会这样吗?
发布于 2010-03-12 07:32:38
当我尝试这样做时,我得到了一个不同的错误:
'Border' object cannot be added to 'DerivedTemplate'.
Object of type 'System.Windows.Controls.Border' cannot be converted
to type 'System.Windows.FrameworkElementFactory'.查看FrameworkElementFactory,这似乎是一种在代码中创建模板的旧方法:
此类是一种以编程方式创建模板的已弃用方式,这些模板是FrameworkTemplate的子类,如ControlTemplate或DataTemplate;使用此类创建模板时,并非所有模板功能都可用。
我的问题是,你为什么要继承ControlTemplate?我想不出这样做的用例。如果您只是尝试在代码隐藏中创建自己的模板,MSDN建议使用以下方法:
以编程方式创建模板的推荐方法是使用XamlReader类的load方法从字符串或内存流加载XAML。
https://stackoverflow.com/questions/2427663
复制相似问题