代码之家  ›  专栏  ›  技术社区  ›  Bhuvan

WPF列表框复制到剪贴板

  •  11
  • Bhuvan  · 技术社区  · 14 年前

    我正试图复制一个标准的WPF列表框选定的项目(显示)文本到剪贴板上的CTRL+C。有没有任何简单的方法来实现这一点。如果它对应用程序中的所有列表框都有效。。那太好了。

    提前谢谢。

    1 回复  |  直到 13 年前
        1
  •  21
  •   eagleboost    14 年前

    因为你在WPF,所以你可以尝试附加的行为
    首先你需要这样一门课:

    public static class ListBoxBehaviour
    {
        public static readonly DependencyProperty AutoCopyProperty = DependencyProperty.RegisterAttached("AutoCopy",
            typeof(bool), typeof(ListBoxBehaviour), new UIPropertyMetadata(AutoCopyChanged));
    
        public static bool GetAutoCopy(DependencyObject obj_)
        {
            return (bool) obj_.GetValue(AutoCopyProperty);
        }
    
        public static void SetAutoCopy(DependencyObject obj_, bool value_)
        {
            obj_.SetValue(AutoCopyProperty, value_);
        }
    
        private static void AutoCopyChanged(DependencyObject obj_, DependencyPropertyChangedEventArgs e_)
        {
            var listBox = obj_ as ListBox;
            if (listBox != null)
            {
                if ((bool)e_.NewValue)
                {
                    ExecutedRoutedEventHandler handler =
                        (sender_, arg_) =>
                        {
                            if (listBox.SelectedItem != null)
                            {
                                //Copy what ever your want here
                                Clipboard.SetDataObject(listBox.SelectedItem.ToString());
                            }
                        };
    
                    var command = new RoutedCommand("Copy", typeof (ListBox));
                    command.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Control, "Copy"));
                    listBox.CommandBindings.Add(new CommandBinding(command, handler));
                }
            }
        }
    }
    


    那么你有这样的XAML

    <ListBox sample:ListBoxBehaviour.AutoCopy="True">
      <ListBox.Items>
        <ListBoxItem Content="a"/>
        <ListBoxItem Content="b"/>
      </ListBox.Items>
    </ListBox>
    


    更新:对于最简单的情况,可以通过以下方式访问文本:

    private static string GetListBoxItemText(ListBox listBox_, object item_)
    {
      var listBoxItem = listBox_.ItemContainerGenerator.ContainerFromItem(item_)
                        as ListBoxItem;
      if (listBoxItem != null)
      {
        var textBlock = FindChild<TextBlock>(listBoxItem);
        if (textBlock != null)
        {
          return textBlock.Text;
        }
      }
      return null;
    }
    
    GetListBoxItemText(myListbox, myListbox.SelectedItem)
    FindChild<T> is a function to find a child of type T of a DependencyObject