locked
Add Ctrl+C functionality to a textblock RRS feed

  • Question

  • I have a TextBlock which looks like this

    <StackPanel Style="{StaticResource SummaryStyle}">
       <TextBlock Text="{Binding Path=UsedFor, Mode=OneWay}"
                 Style="{StaticResource SummaryStyle}"
       Visibility="{BindingPath=IsPreferred}" />
       <TextBlock Text="{Binding Path=UsedFor, Mode=OneWay}"
                   Style="{StaticResource SummaryStyle}"
             Visibility="{Binding Path=IsPreferred}" />
     </StackPanel>

    How do I add Ctrl +C functionality to the textblock, so that when someone clicks on the Textblock, they can copy the text in it

    Monday, March 11, 2013 10:45 PM

Answers

  • Hello !

    Two ideas...

    The first is here:

    XAML:

        <Grid>
            <Grid.Resources>
                <ContextMenu x:Key="MyContextMenu">
                    <MenuItem Header="Copy" Click="Copy_Click"/>
                </ContextMenu>
            </Grid.Resources>
    
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="Copy me!" ContextMenu="{StaticResource MyContextMenu}"/>
            
        </Grid>

    C#:

            private void Copy_Click(object sender, RoutedEventArgs e)
            {
                var menuItem = sender as MenuItem;
                var contextMenu = menuItem.Parent as ContextMenu;
                var textBlock = contextMenu.PlacementTarget as TextBlock;
                Clipboard.SetText(textBlock.Text);
            }

    The second is that you could use a TextBox with IsReadOnly = true instead of a Textblock.

    Monday, March 11, 2013 11:20 PM