【发布时间】:2016-10-11 14:02:25
【问题描述】:
我必须使用无法更改的 UserControl。此 UserControl 的 Datacontext 在其构造函数中设置为自身。
public ParameterControl()
{
Datacontext = this;
}
UserControl 应该是我的 ListBox-Items 的模板。
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<parameterControl:ParameterControl
DataContext="{Binding ElementName=StepView, Path=Datacontext.SelectedStep}" //this doesn't work
</parameterControl:ParameterControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我为数据上下文实现的绑定不起作用。
有谁知道我可以如何解决这个问题或告诉我数据上下文设置的时间点?
感谢您的帮助, 亚历克斯
编辑:
你好,
没有机会重建 ParameterControl。 我有这个想法...
<ListBox
ItemsSource="{Binding Parameters}"
<ListBox.ItemTemplate>
<DataTemplate>
<parameterControl:ParameterControl
ParamName="{Binding <!--To the item in the ItemsSource-Collection-->}"
</parameterControl:ParameterControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
参数 Control 只需要正确显示 ParamName 属性的名称。 而这个名字在 ItemsSource-Collection 的 item 中。
现在有人怎么绑定吗?
谢谢你的帮助,亚历克斯
【问题讨论】:
-
创建用户控件的方式不正确,因此我们可以提供的任何建议都必须基于用户控件的错误设置,而我们无法在不知情的情况下提供更多关于它,DataContext 应该默认为 parent.DataContext,除非被覆盖
-
Path=Datacontext.SelectedStep:应该是DataContext。是问题还是实际代码中的错字?如果您不在数据模板中使用ParameterControl,绑定是否有效?尝试用smth simple(例如标签)替换它并测试绑定 -
在 ItemsControl 的 ItemTemplate 中使用的 UserControl 不得显式设置其 DataContext,因为这样做会阻止从项目容器(例如此处的 ListBoxItem)继承 DataContext。
-
@ASh:Datacontext 只是一个错字。
标签: c# wpf user-controls