从浏览器拖放后如何防止URL文本粘贴到WPF文本框中

时间:2019-02-21 22:25:05

标签: c# wpf xaml drag-and-drop

我有一个WPF应用程序,它可以检测用户何时执行了从Web浏览器URL地址行到WPF文本框的拖放操作。我遇到的问题是,在捕获放置事件后,来自浏览器的URL文本将粘贴到WPF文本框中。

我不希望发生这种情况,因为捕获事件后,我将网页源代码下拉到WPF文本框中。将文本放下后,WPF会自动将URL从浏览器URL地址粘贴到当前放置鼠标的TextBox中。

此操作的结果是,我在TextBox中拥有了网页源,然后根据鼠标的位置将页面URL粘贴到下载的页面内容中的某个位置。

如何防止从浏览器拖放的URL文本在拖放后粘贴到WPF文本框中?

以下是我正在使用的WPF事件:

   private void InfoTextBox_DragOver(object sender, System.Windows.DragEventArgs e)
    {
      if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
        e.Effects = System.Windows.DragDropEffects.Copy;
      else
        e.Effects = System.Windows.DragDropEffects.None;

      e.Handled = true;
    }

    private void InfoTextBox_DragEnter(object sender, System.Windows.DragEventArgs e)
    {
      if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
        e.Effects = System.Windows.DragDropEffects.Copy;
      else
        e.Effects = System.Windows.DragDropEffects.None;

      e.Handled = true;
    }

    private void InfoTextBox_PreviewDragOver(object sender, System.Windows.DragEventArgs e)
    {
     e.Handled = true;
    }

    private void InfoTextBox_PreviewDrop(object sender, System.Windows.DragEventArgs e)
    {
      string[] filenames = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);

      if (filenames != null)
      { //This is a drag drop for a file from File Explorer
        InfoTextBox.Text = File.ReadAllText(filenames[0]);
      }
      else
      {
        string aUrl = (string)e.Data.GetData(System.Windows.DataFormats.StringFormat);
        if (aUrl != null)
        { //This is a drag drop for a URL from the browser
          WebClient myClient = new WebClient();
          Stream response = myClient.OpenRead(aUrl);

          // convert stream to string
          StreamReader reader = new StreamReader(response);
          string text = reader.ReadToEnd();
          InfoTextBox.Text = text;

          response.Close();
        }
      }
    }

以下是InfoTexTBox的XAML:

<TextBox x:Name="InfoTextBox" Grid.Column="1" Grid.ColumnSpan="3" 
             Grid.Row="5" Grid.RowSpan="7" 
             DragEnter="InfoTextBox_DragEnter" 
             PreviewDrop="InfoTextBox_PreviewDrop"
             PreviewDragOver="InfoTextBox_PreviewDragOver"
             HorizontalAlignment="Stretch" Margin="5,0,-8,80" BorderBrush="PowderBlue"
             BorderThickness="1" VerticalScrollBarVisibility="Auto" 
             TextWrapping="Wrap" AcceptsReturn="True" 
             Text="" VerticalAlignment="Stretch"   />

谢谢。

0 个答案:

没有答案