WPF UserControl in DataTemplate within ItemsControl - how to bind to parent of ItemsSource

J Stewart picture J Stewart · Sep 18, 2009 · Viewed 9.6k times · Source

The subject line says it all really! I have a user control which can be bound successfully to, say, a Fullname object - i.e. it works ok.

I now need to show a list of these and, again, this works ok when the control is in a DataTemplate within ItemsControl.Template.

But, the control has a property (InEditMode) that is not a property of the Fullname object but of the object that has the FullnameList property to which the ItemsControl is bound, via ItemsSource. This InEditMode property works fine when the control is not in a list and is bound to parent sibling properties named, say, ParentInEditMode and ParentFullname.

The question is - what style of binding expression is required to 'get at' the edit mode property of the parent object when the control is an ItemsControl?

Or, should I re-design the Fullname object to contain an EditMode property?

Many thanks in advance!

Update:

The item (i.e. that which is in collection bound to the ItemsControl) does NOT have such a property. Code is very simple:

<ItemsControl ItemsSource="{Binding Path=FullnameList}"> 
...then...
<ItemsControl.ItemTemplate>
  <DataTemplate>
    <jasControls:NameView
      NameValue="{Binding Path=.}" 
      InEditMode= ??????? />

The overall parent (the viewmodel for the window) has properties:

  • FullnameList

  • ParentInEditMode

  • Fullname (single item for testing NameView which works perfectly with this xaml outside of any list control using:

     <jasControls:NameView NameValue="{Binding Path=Fullname}" InEditMode="{Binding Path=ParentInEditMode}"/>
    

I would like to apply the edit mode to the entire collection - making that flag part of Fullname does not seem right!?

Answer

J Stewart picture J Stewart · Sep 18, 2009

I have found an answer to my own question, which I hope will help others. The working syntax I have is this:

<StackPanel>
    <ItemsControl ItemsSource="{Binding Path=FullnameList}">
    ...then...
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <jasControls:NameView
          NameValue="{Binding Path=.}" 
          InEditMode= "{Binding DataContext.ParentInEditMode,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}}" />

This correctly picks up the property that is a sibling of FullnameList and passes it to the data template item. More by luck than judgement, but I hope this is a valid way to do this!