【问题标题】:Obtain ListBox SelectedItem through ContextMenu with Multibinding in Windows.Resource在 Windows.Resource 中通过 ContextMenu 和 Multibinding 获取 ListBox SelectedItem
【发布时间】:2019-03-27 14:11:34
【问题描述】:

我正在尝试在 Window.Resources 中存储的上下文菜单上使用多重绑定,但我不知道如何获取我将菜单附加到的 ListBox 的 SelectedItem。

我想我需要使用 PlacementTarget,但什么都做不了。我尝试使用 FindAncestor,但没有奏效。我也尝试通过 ElementName 获取列表框,但无济于事。

<Window ...>
    <Window.DataContext>
        <local:IPViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <sys:Int32 x:Key="Number">0</sys:Int32>
        <sys:Int32 x:Key="NumberLetter">1</sys:Int32>
        <sys:Int32 x:Key="NumberLetterNumber">2</sys:Int32>

        <local:CombineParams x:Key="CombineParams"/>

        <ContextMenu x:Key="DetailMenu">            
            <MenuItem Header = "Number">
                <i:Interaction.Triggers>                    
                    <i:EventTrigger EventName="Click">
                        <i:InvokeCommandAction Command="{Binding SwitchLabelMode}">
                            <i:InvokeCommandAction.CommandParameter>                                
                                <MultiBinding Converter="{StaticResource CombineParams}">
                                    <!-- The next line is where I'm not sure what to write to get to the listbox -->
                                    <Binding Source="{RelativeSource AncestorType={x:Type ListBox}}"/>                                  
                                    <Binding Source="{StaticResource Number}"/>
                                </MultiBinding>
                            </i:InvokeCommandAction.CommandParameter>
                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </MenuItem>
            ...
    </Window.Resources>

    ...
            <ListBox Name="IndexDetailsListBox"
                    ...
                     ContextMenu="{StaticResource DetailMenu}"
                     ...>

            </ListBox>
...    
</Window>

除了未设置的值之外,我无法让它返回任何东西。 我很感激任何帮助。我发现的其他问题都没有 Window.Resources with MultiBinding 中的上下文菜单,这似乎是我的问题。

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    您的问题是,您将RelativeSource- 对象分配给Source 对象的Source 属性。 RelativeSource- 对象属于 RelativeSource- 属性。
    所以你得到你的List 到多值转换器:

    <MultiBinding Converter="{StaticResource CombineParams}">
        <Binding Path="PlacementTarget" RelativeSource="{RelativeSource AncestorType={x:Type ContextMenu}}"/>
        <Binding Source="{StaticResource Number}"/>
    </MultiBinding>
    

    【讨论】:

    • 效果很好。非常感谢。我会支持你,但它不会让我的声望低于 15。
    猜你喜欢
    • 2014-08-17
    • 2013-04-25
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多