Copy Property to Clipboard

你说的曾经没有我的故事 提交于 2020-01-03 03:39:26

问题


I have a string property in my ViewModel/Datacontext and want a simple button that copies its contents to the clipboard. Is this possible to do from XAML, or I do I need to handle the button click event (or use an ICommand) to accomplish this? I thought the following would work, but my button is always greyed out:

    <Button Width="100" Content="Copy" Command="ApplicationCommands.Copy" 
CommandTarget="{Binding MyStringProperty}"/>

回答1:


The ApplicationCommands are expecting to be in a Toolbar or Menu which will give them FocusScope based on RoutedUICommands. If your button is outside a Toolbar or Menu, then you need to explicitly declare the focus scope:

<Button 
  Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"
  Command="ApplicationCommands.Copy" 
  FocusManager.IsFocusScope="True"/>

The CommandTarget is used to declare which element will provide the FocusScope which means that the Copy button will only be enabled whenever the element declared in the CommandTarget has focus, and in the case of copy, has text highlighted:

<Button 
  Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"
  Command="ApplicationCommands.Copy"
  CommandTarget="{Binding ElementName=MyElement}" />

In answer to your specific question, you'd need to intercept the ApplicationCommands.Copy command to get/set your ViewModel's MyStringProperty; and to be honest, I'm not sure where to even start to figure that one out. Maybe someone smarter around here could provide that piece of the puzzle.



来源:https://stackoverflow.com/questions/2563282/copy-property-to-clipboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!