问题
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