WindowsForms では、次のサンプル コードを使用します。
textBox.Paste("some text");
WPFに同じ機能を持つTextBoxメソッドはありますか? または良い回避策はありますか?
クリップボードクラスを使用します。
textBox1.Text = Clipboard.GetText();
または、テキストボックスのSelectedTextプロパティを使用します。
textBox1.SelectedText = "some text";
public static void Paste(this TextBox textbox, string textToInsert)
{
int caretIndex = textbox.CaretIndex;
string textBoxContent;
if (textbox.SelectedText.Length > 0)
{
textBoxContent = textbox.Text.Remove(caretIndex, textbox.SelectedText.Length);
}
else
{
textBoxContent = textbox.Text;
}
textbox.Text = textBoxContent.Insert(caretIndex, textToInsert);
textbox.CaretIndex = caretIndex + textToInsert.Length;
}