Neste artigo veremos como copiar textos para a área de transferência em suas aplicações Xamarin.Forms.
ADICIONANDO O NUGET PACKAGE
Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”.
Digite “Xamarin.Plugins.Clipboard” e selecione o plugin como demonstrado na imagem a seguir.
Selecione todos os projetos e clique no botão “Install”.
Referencie o plugin “Plugin.Clipboard” e utilize:
- CrossClipboard.Current.SetText(“Texto para copiar”)
Para copiar para a área de transferência.
- CrossClipboard.Current.GetText()
Para pegar o texto da área de transferência.
No exemplo a seguir, eu utilizo o texto digitado pelo usuário em um Entry, copiando para a área de transferência e em seguida mostro o texto que se encontra na área de transferência utilizando um DisplayAlert.
C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Plugin.Clipboard; | |
using System; | |
using Xamarin.Forms; | |
namespace ClipboardDemo | |
{ | |
public partial class MainPage : ContentPage | |
{ | |
public MainPage() | |
{ | |
InitializeComponent(); | |
} | |
private async void Copy(object sender, EventArgs e) | |
{ | |
CrossClipboard.Current.SetText(Mensagem.Text); | |
await DisplayAlert("Atenção", "O Texto \"" | |
+ CrossClipboard.Current.GetText() | |
+ "\" foi copiado.", "OK"); | |
} | |
} | |
} |
Xaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
xmlns:local="clr-namespace:ClipboardDemo" | |
x:Class="ClipboardDemo.MainPage"> | |
<ContentPage.Content> | |
<StackLayout> | |
<Entry x:Name="Mensagem"/> | |
<Button Text="Copiar" Clicked="Copy"/> | |
</StackLayout> | |
</ContentPage.Content> | |
</ContentPage> |
Resultado
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.