views:

1092

answers:

1

Hello!

I've got a very simple WPF UserControl that looks like this:

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;
    }
  }
}

However, when I try to do this in the XAML of the Window in which the UserControl is sitting:

<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>

I get the following errors:

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'.

There must be simple way to get the above to work, but I'm afraid I haven't been able to find any relevant info on the subject. Can anybody please give me a pointer or two?

Many thanks!

+2  A: 

The syntax Type.Property is used to set attached properties. Try this instead:

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

HTH, Kent

Kent Boogaart
Thanks Kent, that seems to work fine. I had understood from this URL http://msdn.microsoft.com/en-us/library/ms752059.aspx#properties that the Attribute Syntax and the Property Element Syntax were interchangeable. Do you have a better link to explain the differences?
Shunyata Kharg
You weren't using property element syntax though. That would imply having a Composite.Color child element inside the UserControl1 element (not an attribute).
Kent Boogaart