【WPF】ListBoxItemのインデックスをContextMenuのCommandParameterにBindingする方法
ListBoxのインデックス
ListBoxのインデックスを取得する方法
ListBoxのインデックスはListBox
のAlternationCount
プロパティとAlternationIndex
添付プロパティの組み合わせで取得できます。
{Binding Path="(ItemsControl.AlternationIndex)" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}"}
参考:
https://qiita.com/tera1707/items/791bdb887eae4c0ea6a4
ContextMenuでの対応
しかし、ContextMenu
ではツリーが別になるためPlacementTarget
などを駆使してDataContextなどを受け渡す必要があります。
そうするとListBoxItem
を取得できるのはContextMenu.PlacementTarget
になりますが、PlacementTarget.(ItemsControl.AlternationIndex)
とすることでAlternationIndex
添付プロパティが取得できます。
例
<ListBox
ItemsSource="{Binding Items}"
AlternationCount="1000">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter
Property="Tag"
Value="{Binding DataContext,RelativeSource={RelativeSource AncestorType=Window}}"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem
Header="{x:Static properties:Resources.Delete}"
Command="{Binding RemoveCommand}"
CommandParameter="{Binding PlacementTarget.(ItemsControl.AlternationIndex), RelativeSource={RelativeSource AncestorType=ContextMenu}}"
/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Author And Source
この問題について(【WPF】ListBoxItemのインデックスをContextMenuのCommandParameterにBindingする方法), 我々は、より多くの情報をここで見つけました https://qiita.com/naminodarie/items/524ee5bbdb687567715e著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .