【问题标题】:WPF: programmatically opening context menu loses data contextWPF:以编程方式打开上下文菜单会丢失数据上下文
【发布时间】:2021-12-13 15:54:24
【问题描述】:

我想重用 ListViewItem 的上下文菜单,方法是在项目本身内添加一个切换按钮来打开它。 上下文菜单本身可以正常工作, 但是,当我通过切换按钮打开它时(只需将其属性 IsOpen 设置为 True),里面的命令就不再起作用了。 似乎上下文菜单不再有DataContext

<ListView>
 <ListView.ItemContainerStyle>
     <Style TargetType="{x:Type ListViewItem}">
         <Setter Property="ContextMenu">
             <Setter.Value>
                 <ContextMenu>
                     <MenuItem
                         Header="Restore"
                         Command="{Binding RestoreCommand}" />
                     <MenuItem
                         Header="Delete"
                         Command="{Binding DeleteCommand}"/>
                 </ContextMenu>
             </Setter.Value>
         </Setter>
     </Style>
 </ListView.ItemContainerStyle>

 <ListView.View>
     <GridView>
         <!-- My columns here -->
         <GridViewColumn>
             <GridViewColumn.CellTemplate>
                 <DataTemplate>
                     <ToggleButton IsChecked="{Binding Path=ContextMenu.IsOpen, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"/>
                 </DataTemplate>
             </GridViewColumn.CellTemplate>
         </GridViewColumn>
     </GridView>
 </ListView.View>

有什么建议吗? 谢谢

【问题讨论】:

    标签: wpf xaml datacontext


    【解决方案1】:

    问题在于以这种方式间接打开的上下文菜单没有DataContext。 为了“分配”它一个,您应该使用属性PlacementTarget 来指示它绑定到哪个控件。

    要完成此任务,您可以创建自定义行为,或者,如果您更喜欢纯 xaml 解决方案:

    <!-- xmlns:b="http://schemas.microsoft.com/xaml/behaviors" -->
     
    <GridViewColumn>
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <ToggleButton
                x:Name="MoreActionsButton"
                IsChecked="{Binding ContextMenu.IsOpen, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Mode=OneWayToSource}">
                <b:Interaction.Triggers>
                    <b:EventTrigger EventName="Checked">
                        <b:ChangePropertyAction
                            TargetObject="{Binding ContextMenu, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"
                            PropertyName="PlacementTarget"
                            Value="{Binding ElementName=MoreActionsButton}" />
                    </b:EventTrigger>
                </b:Interaction.Triggers>
            </ToggleButton>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
    </GridViewColumn>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多