2016-07-20 1 views
0

자식 컨테이너를 다른 컨테이너에서 드래그 할 때 자식 객체를 부모 컨테이너로 캐스트 할 수 있습니까? 여기 내가하려는 일이 있습니다.자식 객체를 드래그 된 객체에서 부모 객체로 캐스트 - C# WPF

  1. 나는 2. 클래스 1 개체를 파생하고 다른 목록 상자에서 드롭을 시도으로 드래그
  2. , 내가 할 개체가 유형 인 목록 파생 클래스 하나의 객체를 가진 상자와 파생 클래스가 마찬가지로 파생 클래스 2 객체를 드래그하면 파생 클래스 2가됩니다.

ItemSource는 ObservableCollection에에 바인더 제본 한 다른 목록 상자에서 낙하하는 동안, 나는 기본 클래스에 이러한 파생 클래스 객체를 캐스팅합니다.

참고 : 드래그 한 객체에 typeof 연산자가있는 기본 클래스를 사용할 때 null이 반환됩니다. 여기

는 xaml.cs에서

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

    public class DerivedClassOne : BaseClass 
    { 

    } 

    public class DerivedClassTwo : BaseClass 
    { 

    } 

이벤트 핸들러 파일

<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" }); 
     } 

자료 바인더 제본 속성과 상속 클래스 내 XAML입니다

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); 

    } 

여기서 드래그 된 객체로 얻는 데이터는 DerivedClassOne 또는 DerivedClassTwo이므로 파생 클래스 1 또는 파생 클래스 2를 드래그 할 때마다 droppedObject가 null이됩니다.

삭제하는 동안 이러한 파생 개체를 부모에게 어떻게 캐스트 할 수 있는지 제안 해주십시오.

+2

디버깅 중에 'e.Data'의 내용을 볼 수 있습니까? – bit

+0

예. 드래그 된 객체 정보를 e.Data에서 볼 수있었습니다. ie 'Derived Class 1'을 드래그하면 e.Data에 'DerivedClassOne'이 표시됩니다. –

답변

0

DragEventArgs에는 문자열 배열을 반환하는 .GetFormats 함수가 있으며 각 문자열에는이 데이터 객체에서 지원하는 형식의 이름이 지정됩니다.

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

당신은 당신에게 자료 개체 또는 아무것도 ... 모든 알려진 파생 클래스의 정확한 검사없이 얻을 :

은 그럼 당신은 선택이 문자열을 사용하고 드롭 데이터 콘텐츠를 변환 할 수 있습니다.

관련 문제