【问题标题】:Cast child object to parent in dragged object - C# WPF将子对象转换为拖动对象中的父对象 - C# WPF
【发布时间】:2016-07-20 06:01:56
【问题描述】:

当子对象被从一个容器拖到另一个容器时,我们可以将子对象转换为它的父对象吗?这是我想要做的。

  1. 我有一个列表框,其中包含派生类 1 和派生类 2 的对象。
  2. 当我拖动派生类 1 对象并尝试拖放到另一个列表框时,我得到的对象是派生类 1 类型。同样,当我拖动派生类 2 对象时,它是派生类 2。

在将 ItemSource 绑定到 ObservableCollection 的另一个列表框中放置时,我想将这些派生类对象强制转换为基类。

注意:当我将基类与 typeof 运算符与拖动对象一起使用时,我会得到 null。

这是我的 XAML

<GroupBox Header="BaseClassObjects" >
        <ListBox SelectedIndex="0" ItemsSource="{Binding BaseClassList}" DisplayMemberPath="Name" PreviewMouseLeftButtonDown="protocol_PreviewMouseLeftButtonDown">
        </ListBox>
    </GroupBox>





  <GroupBox Header="Drop Here" >
                <ListBox AllowDrop="True" Drop="ports_Drop">
                </ListBox>
            </GroupBox>

视图模型中的绑定属性

ObservableCollection<BaseClass> baseClassList = new ObservableCollection<BaseClass>();

        public ObservableCollection<BaseClass> BaseClassList
        {
            get { return baseClassList; }
            set { baseClassList = value; }
        }

 public VM_DragDrop()
        {
            BaseClassList.Add(new DerivedClassOne() { Name = "Derived Class 1" });
            BaseClassList.Add(new DerivedClassTwo() { Name = "Derived Class 2" });
        }

基类和派生类

  public class BaseClass
    {
        public string Name { get; set; }
    }

    public class DerivedClassOne : BaseClass
    {

    }

    public class DerivedClassTwo : BaseClass
    {

    }

xaml.cs 文件中的事件处理程序

private void protocol_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListBox listbox = (sender as ListBox);
            DragDrop.DoDragDrop(listbox, listbox.SelectedItem, DragDropEffects.Copy);
        }

 private void ports_Drop(object sender, DragEventArgs e)
        {
            BaseClass droppedObject = (BaseClass)(e.Data.GetData(typeof(BaseClass)));
            (sender as ListBox).Items.Add(droppedObject);

    }

这里,当我拖动 Derived Class 1 或 Derived Class 2 时,dropObject 将为空,因为我们通过拖动对象获得的数据是 DerivedClassOne 或 DerivedClassTwo。

请建议我们如何在放置时将这些派生对象转换为父对象。

【问题讨论】:

  • 调试的时候能看到e.Data的内容吗?
  • 是的。我可以在 e.Data 中看到拖动的对象信息。即当我拖动“Derived Class 1”时,我在 e.Data 中看到“DerivedClassOne”

标签: c# wpf


【解决方案1】:

DragEventArgs 有一个 .GetFormats 函数返回一个字符串数组,每个字符串指定此数据对象支持的格式的名称。

然后你可以使用这个字符串来拾取和转换drop数据内容:

Dim tmpTypes() As String = e.Data.GetFormats
Dim tmpTyp As String = tmpTypes(0)
Dim dropper As MyObjectBase = TryCast(e.Data.GetData(tmpTyp), MyObjectBase)

你得到你的 Base 对象或什么都没有......没有对所有已知的派生类进行精确测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    相关资源
    最近更新 更多