简体   繁体   English

设置动态创建的控件的数据上下文

[英]Setting the Datacontext of a dynamically created control

I have a UserControl (Map) that contains a Canvas control. 我有一个包含Canvas控件的UserControl(地图)。 I am dynamically adding a control (Gate) to this canvas from the code behind. 我正在从后面的代码向此画布动态添加一个控件(Gate)。

I want the Gate objects DataContext to be the "Gate" property of the Map's DataContext. 我希望Gate对象的DataContext成为地图的DataContext的“门”属性。 This is being done in the code behind. 这是在后面的代码中完成的。

 Binding dataContextBinding = new Binding();
        dataContextBinding.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
        dataContextBinding.Path = new PropertyPath("DataContext.SelectedLevelModule.Gate");
        dataContextBinding.Mode = BindingMode.TwoWay;
        dataContextBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(gate, DataContextProperty, dataContextBinding);

After this block of code runs, the gate.DateContext is null... Any ways this can be done? 在这段代码运行之后,gate.DateContext为空...可以采取任何方法吗? Drawing a blank.. Thanks Harold 画一个空白..谢谢哈罗德

You are setting the property path to DataContext.SelectedLevelModule.Gate . 您正在将属性路径设置为DataContext.SelectedLevelModule.Gate You are then assigning the binding to the DataContextProperty . 然后,您将绑定分配给DataContextProperty I think what is happening is that the path is now gate.DataContext.DataContext.SelectedLevelModule.Gate . 我认为发生的事情是该路径现在是gate.DataContext.DataContext.SelectedLevelModule.Gate

Try removing DataContext from your PropertyPath and see if that fixes it. 尝试从PropertyPath删除DataContext,看看是否可以解决。 You are already assigning it to the DataContext, you should not have to specify it in the Path. 您已经将它分配给DataContext,不必在Path中指定它。

var dataContextBinding = new Binding();
dataContextBinding.Path = new PropertyPath("SelectedLevelModule.Gate");
BindingOperations.SetBinding(gate, DataContextProperty, dataContextBinding);

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

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