简体   繁体   English

将依赖项属性绑定为数据上下文

[英]Binding a Dependencyproperty as the Datacontext

I am building a custom control with a Dependencyproperty. 我正在构建一个具有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. 我希望dependencyproperty是控件中容器的数据上下文。但是当我用控件创建视图并绑定属性时,它不起作用。 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). 在控件的xaml中,我有一个用于存放项目的容器(ControlItemHost)。

When I build the main view and initialize the property: MyItems="{Binding ListOfItems}" 当我构建主视图并初始化属性时:MyItems =“ {Binding ListOfItems}”

I dont see the items, but if I add in MyControl items I see them. 我没有看到这些项目,但是如果添加MyControl项目,则会看到它们。 How do I fix this so that I can bind from outside the control? 如何解决此问题,以便可以从控件外部进行绑定?

(It is necessary that the property will be the datacontext) (该属性必须是数据上下文)

You are only assigning a constant value to the DataContext property, instead of establishing a binding. 您仅将常量值分配给DataContext属性,而不是建立绑定。 Try the following: 请尝试以下操作:

ControlItemHost.SetBinding(FrameworkElement.DataContextProperty, new Binding("MyItems") { Source = this });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM