簡體   English   中英

將 Button 內的 ContextMenu Item 綁定到 ViewModel

[英]Bind ContextMenu Item inside Button to ViewModel

我正在嘗試將帶有ItemMenuContextMenu添加到按鈕

<Button x:Name="RemoteMachine" Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}" CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" CommandParameter="{Binding}"
                      Command="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

在我的 model 中,我有以下內容

public ICommand RemoteMachineSelectedCommand => new CommandHandler(p => MachineSelectedAction(p, true), true);
public ICommand DeleteRemoteMachineCommand => new CommandHandler(p => DeleteRemoteMachineAction(p), true);

Button 命令可以正常工作,而 ContextMenu 則不能。 我想我在某種程度上錯誤地綁定了它。

有什么建議嗎?

您可以將ButtonTag屬性綁定到命令,然后使用父級ContextMenuPlacementTarget屬性從MenuItem綁定到它:

<Button x:Name="RemoteMachine"
        Tag="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"
        Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}"
        CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete"
                              CommandParameter="{Binding PlacementTarget.CommandParameter,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                              Command="{Binding PlacementTarget.Tag,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM