Change Datacontext of a UserControl

我的梦境 提交于 2020-03-15 07:36:47

问题


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;
}

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

EDIT:

Hi again,

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>

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.

Do anyone now how to bind?

Thanks for help, Alex


回答1:


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).

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}}"/>

where SomeText is a property of the UserControl class.

As a general rule, never set the DataContext property of a UserControl explicitly.



来源:https://stackoverflow.com/questions/39979067/change-datacontext-of-a-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!