更改用户控件的数据上下文 [英] Change Datacontext of a UserControl
问题描述
我必须使用无法更改的 UserControl.此 UserControl 的 Datacontext 在其构造函数中设置为自身.
I have to work with a UserControl, that I cannot change. The Datacontext of this UserControl is set to itself in its constructor.
public ParameterControl()
{
Datacontext = this;
}
UserControl 应该是我的 ListBox-Items 的模板.
The UserControl should be the template of my 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>
我实现的数据上下文绑定不起作用.
My implemented binding for the datacontext doesn't work.
有谁知道我如何解决这个问题或告诉我数据上下文是在什么时间点设置的?
Does anyone know how I can solve this problem or tell me at what point of time the datacontexts are set?
感谢您的帮助,亚历克斯
Thanks for help, Alex
你好,
没有机会重建ParameterControl.我有这个想法...
there is no chance to rebuild the ParameterControl. I've got this idea...
<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中.
The parameter Control needs only the name for the ParamName property to be displayed correctly. And this name is in the item of the ItemsSource-Collection.
现在有人怎么绑定吗?
感谢您的帮助,亚历克斯
Thanks for help, Alex
推荐答案
在 ItemsControl 的 ItemTemplate 中使用的 UserControl 不得显式设置其 DataContext
属性,因为这样做会阻止继承 DataContext来自项目容器(例如这里的 ListBoxItem).
A UserControl that is used in the ItemTemplate of an ItemsControl must not explicitly set its DataContext
property, because doing so prevents inheriting the DataContext from the item container (e.g. the ListBoxItem here).
此问题唯一有效的解决方案是从 UserControl 的构造函数中删除 DataContext 分配,并用 RelativeSource
或 ElementName
替换任何可能的内部"基于 DataContext 的绑定> 绑定,比如
The only valid solution for this problem is to remove the DataContext assignment from the UserControl's constructor, and to replace any possible "internal" DataContext-based bindings by RelativeSource
or ElementName
bindings, like
<TextBlock
Text="{Binding SomeText, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
其中 SomeText
是 UserControl 类的属性.
where SomeText
is a property of the UserControl class.
作为一般规则,永远不要显式设置 UserControl 的 DataContext
属性.
As a general rule, never set the DataContext
property of a UserControl explicitly.
这篇关于更改用户控件的数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!