2010-03-11 118 views
1

下面的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

回答

0

我得到一個不同的錯誤,當我試試這個:

'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