我有一个非常简单的WPF UserControl,如下所示:
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;
}
}
}
但是,当我尝试在UserControl所在的窗口的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'.
必须有简单的方法让上述工作,但我担心我无法找到有关该主题的任何相关信息。任何人都可以给我一两个指针吗?
非常感谢!
答案 0 :(得分:4)
语法Type.Property
用于设置attached properties。试试这个:
<test:UserControl1 Name="whatever">
<test:UserControl1.Composite>
<test:Composite Color="Blue"/>
</test:UserControl1.Composite>
</test:UserControl1>