WPF & ldquo; Static & rdquo; Binding in a list

advertisements

I have a problem with a binding in a List.

I have a List of objects. This List is bound to a ListBox. Of every object in my List I can open a ContextMenu:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="ContextMenu">
      <Setter.Value>
        <ContextMenu>
          <MenuItem Header="First"  IsEnabled="{Binding FirstEnabled}"/>
          <MenuItem Header="Second"  IsEnabled="{Binding SecondEnable}"/>
        </ContextMenu>
      </Setter.Value>
    </Setter>
  </Style>
</ListBox.ItemContainerStyle>

In the code like this my objects in the list having the two booleans to bind. Now I want to bind this two booleans not to the objects. I want to bind it "static" to my DataContext. This is not working like this and I have no idea how to realize it.

I googled a lot but found nothing helpful ...

Thanks for helping!


Since, ContextMenu applies to ListBoxItem it will have its DataContext value and ListBoxItem will be its PlacementTarget. So if you want to bind to property of ListBox.DataContext you need to pass current ListBox.DataContext as, for example, Tag to ListBoxItem and then you need to refer to it from ContextMenu via its PlacementTarget. It's all because ContextMenu uses Popup which creates its own visual tree so simple RelativeSource/ElementName binding won't work

<Style TargetType="ListBoxItem">
    <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=DataContext}"/>
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <MenuItem Header="First"  IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Tag.FirstEnabled}"/>
                <MenuItem Header="Second" IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Tag.SecondEnable}"/>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>