Manuel Amstutz
Manuel Amstutz

Reputation: 1388

How to initialize a collection property in a custom WPF control

I have a custom WPF control base class. This base class registers a custom property with the type "List<"some own type">".

How can I initialize the property for design time? There should always be 8 objects in the list and the user should by able to modify this objects.

I have tried to pass a default value with the PropertyMetadata object, but the collection shown in the property editor is always empty.

public class CustomPropertyTestBase : UserControl
{

    static CustomPropertyTestBase()
    {
        List<object> defaultValue = new List<object>(new object[8]);
        MyCustomObjectsProperty = DependencyProperty.Register("MyCustomObjects",
            typeof(List<object>), typeof(CustomPropertyTestBase),
            new PropertyMetadata(defaultValue));
    }

    public static DependencyProperty MyCustomObjectsProperty;

    [Category("MyCustomProperties")]
    public List<object> MyCustomObjects
    {
        get;
        set;
    }
}

EDIT:

Whenever i add a new object in the property editor, these new objects are not stored. After reopening the property editor the list is empty again.

I have attached the debugger to the designer and the get or set methods of the property are never called by the editor.

SOLUTION:

As "dowhilefor" had mentioned. I had to change the type ObservableCollection. Now the designer stores the changed list correctly. Thanks.

Upvotes: 2

Views: 2321

Answers (3)

Manuel Amstutz
Manuel Amstutz

Reputation: 1388

As "dowhilefor" had mentioned. I had to change the type ObservableCollection. Now the designer stores the changed list correctly. Thanks.

Upvotes: 1

user128300
user128300

Reputation:

When you need to show sample data for design time, you should not hardcode the sample data in your C# code.

Instead, use the attribute d:DesignData and a supporting sample data *.xaml file to show sample data in the designer. The article Design-time Attributes shows how to do that.

Here is an additional good article about DesignData: DesignData MVVM support in Blend, VS2010 and ....

Please note that DesignData works not only with Blend, but also in Visual Studio.

Upvotes: 2

dowhilefor
dowhilefor

Reputation: 11051

Something like this should work:

public MainWindow()
    {
        InitializeComponent();

        if( System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
        {
            MyCustomObjects = new List<object>();
            MyCustomObjects.Add("Hello");
        }
    }

But maybe its not the best solution. I remember there was some tools in expression blend to have dummy data, but can't remember how they did it. Of course this is static and you can't change it, but i don't think this is possible.

Upvotes: 1

Related Questions