我对列表中的绑定有问题。
我有一个对象列表。该列表绑定到一个列表框。我可以在列表中的每个对象中打开一个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>
在这样的代码中,列表中的我的对象具有两个要绑定的布尔值。现在,我不想将这两个布尔值绑定到对象。我想将其“静态”绑定到我的DataContext。这不是这样工作的,我也不知道如何实现。
我在Google上搜索了很多,但没有发现任何帮助。
感谢您的帮助!
因为,ContextMenu
适用于ListBoxItem
它将具有它的DataContext
价值,ListBoxItem
并将是它的PlacementTarget
。因此,如果要绑定到的属性,则ListBox.DataContext
需要将currentListBox.DataContext
作为传递Tag
给ListBoxItem
,然后需要通过引用ContextMenu
它PlacementTarget
。这都是因为ContextMenu
使用Popup
它创建自己的可视化树那么简单RelativeSource
/ElementName
装订将无法正常工作
<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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句