Reputation: 538
I have a WPF window with 4 read-only TextBoxes
in it, to all of which I need to enable a context menu with copy option. Currently I'm doing with code behind. But I heard it is not a good approach.
<TextBox Name="StepsTextBox"
Text="{Binding Steps, Mode=OneWay}"
IsReadOnly="True"
Click="Copy_click"/>
Code-Behind:
private void Copy_click(object sender, RoutedEventArgs e)
{
StepsTextBox.Copy();
}
I tried using MVVM as follows:
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="{Binding OnCopyButtonClick}" CommandParameter="{Binding ElementName=StepsTextBox}"/>
</ContextMenu>
</TextBox.ContextMenu>
But how do I access this text box from the code if I pass it as parameter. And also how can I keep this code generic for all the textboxes?. Could anyone help?. Thanks in advance.
private void OnCopyButtonClick(TextBox textBox)
{
//??
}
Upvotes: 0
Views: 379
Reputation: 3741
You can use the build-in ApplicationCommands.Copy. No need to implement anything, the copy functionality is already implemented.
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy" Command="Copy" />
</ContextMenu>
</TextBox.ContextMenu>
You will still have to select the text before copying it, but that's to be expected when copying text.
Upvotes: 1