首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WPF中使用派生ControlTemplates的问题

在WPF中使用派生ControlTemplates的问题
EN

Stack Overflow用户
提问于 2010-03-12 02:37:18
回答 1查看 1.1K关注 0票数 1

下面的xaml代码可以工作:

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
using System.Windows.Controls;

namespace DerivedTemplateBug
{
 public class DerivedTemplate : ControlTemplate
 {
 }
}

然后用ControlTemplate替换派生类:

代码语言:javascript
复制
<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‘。

有人能告诉我为什么会这样吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-03-12 07:32:38

当我尝试这样做时,我得到了一个不同的错误:

代码语言:javascript
复制
'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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2427663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档