2009-01-02 310 views
0

我有一个非常简单的WPF用户控件,看起来像这样:自定义属性的System.Windows.Window

namespace WpfControlLibrary1 
{ 
    public partial class UserControl1 : UserControl 
    { 
    public UserControl1() 
    { 
     InitializeComponent(); 
     Composite = new Composite(); 
     Composite.Color = Colors.Red; 
    } 

    protected override void OnRender(DrawingContext drawingContext) 
    { 
     Draw(drawingContext, new Rect(RenderSize)); 
    } 

    public void Draw(DrawingContext g, Rect rect) 
    { 
     Composite.Draw(g, rect); 
    } 

    public Composite Composite 
    { 
     get; 
     set; 
    } 
    } 

    public class Composite 
    { 
    public void Draw(DrawingContext g, Rect rect) 
    { 
     g.DrawRectangle(new SolidColorBrush(Color), new Pen(Brushes.Black, 1.0), rect); 
    } 

    public Color Color 
    { 
     get; 
     set; 
    } 
    } 
} 

然而,当我尝试这样做在窗口的XAML中在用户控件坐:

<Window x:Class="WpfApplication1.Window2" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:test="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1" 
    Title="Window2" Height="500" Width="700"> 

    <test:UserControl1 Name="uControl1" Composite.Color="Blue"> 
    </test:UserControl1> 
</Window> 

我收到以下错误:

Error 1 The attachable property 'Color' was not found in type 'Composite'. 
Error 2 The property 'Composite.Color' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. 

必须有简单的方式来获得上述工作,但恐怕我一直无法找到任何有关这个问题的相关信息。任何人都可以给我一两个指针吗?

非常感谢!

回答

4

语法Type.Property用于设置attached properties。试试这个:

​​
+0

谢谢肯特,这似乎工作正常。我从这个URL http://msdn.microsoft.com/en-us/library/ms752059.aspx#properties中了解到,属性语法和属性元素语法是可以互换的。你有更好的链接来解释差异吗? – 2009-01-02 19:42:32