Question

I am building a custom control with a Dependencyproperty. I want the dependencyproperty to be the datacontext of a container in my control.But when I Create a view with my control and I bind the property it doesnt work. Code example:

public partial class MyControl : UserControl
{
    public static readonly DependencyProperty MyItemsProperty =  
        DependencyProperty.Register("MyItems", typeof (ObservableCollection <object>), typeof (MyControl), 
        new PropertyMetadata (new ObservableCollection <object>()));

    public ObservableCollection <object> MyItems
    {
        get { return (ObservableCollection <object> GetValue (MyItemsProperty); }
        set { SetValue (MyItemsProperty,  value); }
    }

    public MyControl()
    {
        InitializeComponent();
        ControlItemHost.DataContext =      MyItems;
    }
}

And in the xaml of my control I have a container for the items (ControlItemHost).

When I build the main view and initialize the property: MyItems="{Binding ListOfItems}"

I dont see the items, but if I add in MyControl items I see them. How do I fix this so that I can bind from outside the control?

(It is necessary that the property will be the datacontext)

Was it helpful?

Solution

You are only assigning a constant value to the DataContext property, instead of establishing a binding. Try the following:

ControlItemHost.SetBinding(FrameworkElement.DataContextProperty, new Binding("MyItems") { Source = this });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top