简体   繁体   English

更改用户控件的数据上下文

[英]Change Datacontext of a UserControl

I have to work with a UserControl, that I cannot change.我必须使用无法更改的 UserControl。 The Datacontext of this UserControl is set to itself in its constructor.此 UserControl 的 Datacontext 在其构造函数中设置为自身。

public ParameterControl()
{
    Datacontext = this;
}

The UserControl should be the template of my ListBox-Items. 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>

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感谢您的帮助,亚历克斯

EDIT:编辑:

Hi again,你好,我们又见面了,

there is no chance to rebuild the ParameterControl.没有机会重建 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>

The parameter Control needs only the name for the ParamName property to be displayed correctly.参数 Control 只需要正确显示 ParamName 属性的名称。 And this name is in the item of the ItemsSource-Collection.而这个名字在 ItemsSource-Collection 的项目中。

Do anyone now how to bind?现在有人怎么绑定?

Thanks for help, Alex感谢您的帮助,亚历克斯

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 (eg the ListBoxItem here).在 ItemsControl 的 ItemTemplate 中使用的 UserControl 不得显式设置其DataContext属性,因为这样做会阻止从项目容器(例如此处的 ListBoxItem)继承 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此问题的唯一有效解决方案是从 UserControl 的构造函数中删除 DataContext 分配,并用RelativeSourceElementName绑定替换任何可能的“内部”基于 DataContext 的绑定,例如

<TextBlock
    Text="{Binding SomeText, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

where SomeText is a property of the UserControl class.其中SomeText是 UserControl 类的属性。

As a general rule, never set the DataContext property of a UserControl explicitly.作为一般规则,永远不要显式设置 UserControl 的DataContext属性。

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

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