c# - 在 WPF 和 MVVM 中,如何将 "Copy"上下文菜单添加到 <Hyperlink>?

标签 c# wpf xaml mvvm mvvm-light

在大多数网络现代浏览器中,可以右键单击超链接并使用“复制链接地址...”上下文菜单。

在 WPF 中,我想知道是否有一种方法可以将相同的功能添加到 <Hyperlink> XAML 标记?

我正在使用 MVVM Light。

最佳答案

这实际上比它应该的更难。

原因是ContextMenu is not part of the visual tree ,这意味着尝试使用任何最符合逻辑的绑定(bind)都会返回 null 而不是预期值。

解决方案是将整个 Hyperlink 包装在一个 UserControl 中,然后使用 {Binding PlacementTarget.Content} 来访问我们想要的属性。在这种情况下,必需的属性是 URL,当我们想通过上下文菜单将超链接复制到剪贴板时,我们需要它作为参数。当然,我们可以指定两次 URL,但这违反了 DRY(不要重复自己)原则。

我正在使用 MVVM Light .

XAML

第二个命令参数的目的是绑定(bind)到父Hyperlink标签中NavigateUri的内容,并将其作为上下文菜单的参数,因此可以将其复制到剪贴板上。

<UserControl>
    <Hyperlink NavigateUri="http://www.google.com/" 
               Command="{Binding OnClickHyperlink}"
               CommandParameter="{Binding NavigateUri, RelativeSource={RelativeSource Self}}">
        www.google.com
        <Hyperlink.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Copy link address" 
                          Command="{Binding OnCopyHyperlink}"                                                  
                          CommandParameter="{Binding PlacementTarget.Content.NavigateUri, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
                </MenuItem>
            </ContextMenu>
        </Hyperlink.ContextMenu>
    </Hyperlink>
</UserControl>

用于超链接点击的 C#

private ICommand _onClickHyperlink;
public ICommand OnClickHyperlink
{
    get
    {
        return _onClickHyperlink ?? (_onClickHyperlink = new RelayCommand<Uri>(
            hyperlink =>
            {
                // Handle Hyperlink click here using Process.Start().
            }));
    }
}

用于超链接复制的 C#

private ICommand _onCopyHyperlink;
public ICommand OnCopyHyperlink
{
    get
    {
        return _onCopyHyperlink ?? (_onCopyHyperlink = new RelayCommand<Uri>(
            hyperlink =>
            {
                Clipboard.SetText(hyperlink.OriginalString);
            }));
    }
}

关于c# - 在 WPF 和 MVVM 中,如何将 "Copy"上下文菜单添加到 <Hyperlink>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26593640/

相关文章:

c# - 在异步单元测试中调用 Assert.Inconclusive() 被报告为失败

c# - Windows Phone 8 map 不显示在用户控件中

c# - 客户端服务器套接字应用程序上的方法错误没有过载

c# - 使用 Dependency Property 传递回调方法

c# - 如何使用 Dynamic LINQ 求和

c# - "Are you sure?"提示。 ViewModel 的一部分还是纯粹的 View ?

c# - 为 WPF 开发人员推荐的 Web 技术?

C# 单元测试打开 Window.xaml

c# - 将颜色加载到组合框中

c# - 在嵌套的转发器中使用数据列表项