使用Drag& amp重新排序TreeView降

时间:2017-08-17 15:47:12

标签: c# wpf treeview

我试图达到的最终目标是能够通过将项目拖放到新订单中来重新排序TreeView个项目。当我尝试从TreeViewItem获取原始对象" ModeObject"时,我收到了一个转换错误...我正在{对{做}完全相同的操作{1}}所以我不确定为什么这会给我一个错误。

ListView
  

无法转换类型' MS.Internal.NamedObject'输入   ' ModeObject'

ModeObject mo = (ModeObject)tv.ItemContainerGenerator.ItemFromContainer(tvitem);

<TreeView Grid.Column="1" Name="tvModes" ItemsSource="{Binding Modes}" AllowDrop="True">
  <TreeView.Resources>
     <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
     </Style>
  </TreeView.Resources>

  <TreeView.ItemTemplate>
     <HierarchicalDataTemplate DataType="{x:Type fixtures:ModeObject}" ItemsSource="{Binding Channels}">
        <Grid>
           <TextBlock Text="{Binding Name, Mode=TwoWay}" MouseDown="ModeNameTextBlock_MouseDown" Width="Auto"/>
           <TextBox LostFocus="ModeNameTextBox_LostFocus" KeyDown="ModeNameTextBox_KeyDown" Visibility="Collapsed" Width="Auto"/>
        </Grid>
    </HierarchicalDataTemplate>

   </TreeView.ItemTemplate>
public ObservableCollection<Mode> Modes { get; set; }

...

private void TvModes_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e) {
   Point mousePos = e.GetPosition(null);
   Vector diff = modeReorderStartPoint - mousePos;
   if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed &&
      (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
      Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)) {

      TreeView tv = sender as TreeView;
      TreeViewItem tvitem = FindAncestor<TreeViewItem>((DependencyObject)e.OriginalSource);
      ModeObject mo = (ModeObject)tv.ItemContainerGenerator.ItemFromContainer(tvitem);

      DataObject dragData = new DataObject("reorderMode", mo);
      DragDrop.DoDragDrop((DependencyObject)e.OriginalSource, dragData, DragDropEffects.Move);

   }
}

究竟是什么public class Mode { public string Name { get; set; } public ObservableCollection<ModeObject> Channels { get; set; } public Mode() { Channels = new ObservableCollection<ModeObject>(); } } public class ModeObject { public string Name { get; set; } public int ChannelIndex { get; set; } } 以及如何解决此错误?

1 个答案:

答案 0 :(得分:2)

有点晚了,但对于遇到同样问题的人可能会有用。 由于此树是数据绑定的,因此您可以从其数据上下文而不是ItemContainerGenerator访问每个树项的数据对象。 在提供示例的情况下,旧行:

ModeObject mo = (ModeObject)tv.ItemContainerGenerator.ItemFromContainer(tvitem);

替换为:

ModeObject mo = (ModeObject)tvitem.DataContext;