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