2011-03-15 94 views
0

我目前有一個使用hierarchicaldatatemplate顯示數據的樹視圖,當用戶單擊Remove按鈕時,它將刪除選定的節點。這按預期工作。使用HierarchicalDataTemplate將命令綁定到MenuItem

但是,我沒有讓用戶點擊一個按鈕,而是試圖通過右鍵單擊節點並選擇相應的菜單項來執行該命令。

這被證明是非常困難的,因爲它被一個節點的視圖模型(它不知道任何關於視圖的東西)而不是視圖的相應視圖模型拾取。

有沒有辦法把控制權移交給View的ViewModel呢?

下面是刪除按鈕的代碼:菜單項

public RelayCommand RemoveCommand 
     { 
      get 
      { 
       if (_removeCommand == null) 
       { 
        _removeCommand = new RelayCommand(
         () => this.Remove() 
         ); 
       } 
       return _removeCommand; 
      } 
     } 

     public void Remove() 
     { 
      _organLocationTree2.RemoveOrganLocations(ProjectOrganLocationView.GetExtendedTreeView().SelectedItems); 
      ProjectOrganLocationView.GetExtendedTreeView().SelectedItems.Clear(); 

      base.RaisePropertyChanged("DestOrganTree"); 
     } 

而XAML:

查看:

 <Button Content="Remove" Grid.Row="2" Height="23" VerticalAlignment="Top" Name="removeButton" 
       Width="75" Margin="5,20,5,0" Command="{Binding Path=RemoveCommand}" /> 

視圖模型

  <local:ExtendedTreeView.ItemTemplate> 
       <HierarchicalDataTemplate ItemsSource="{Binding SubOrganLocations}"> 
        <TextBlock Text="{Binding OrganName}" > 
      <TextBlock.ContextMenu> 
       <ContextMenu> 
        <MenuItem Header ="Add SubNode" Command="{Binding Path=MenuItem_Add}"></MenuItem> 
        <MenuItem Header ="Remove Node" Command="{Binding Path=RemoveCommand}"></MenuItem> 
        <MenuItem Header ="Edit Node" Command="{Binding Path=ProjMenuItem_Edit}" 
           CommandParameter="{Binding DestOrganTree, Path=Selected.OrganName}"></MenuItem> 
       </ContextMenu> 
      </TextBlock.ContextMenu> 
        </TextBlock> 
       </HierarchicalDataTemplate> 
      </local:ExtendedTreeView.ItemTemplate> 
     </local:ExtendedTreeView> 

我試圖實施R emove命令在節點的ViewModel中,但由於它不知道任何有關View的內容,所以它很快就變得非常混亂。

回答

2

嗯,我發現我的錯誤,我將上下文菜單綁定到樹的節點而不是樹本身。我在聲明之外移動了上下文菜單,現在它按預期工作。

這是我對別人有此問題的更新XAML:

<local:ExtendedTreeView.ContextMenu> 
         <ContextMenu> 
          <MenuItem Header ="Add SubNode" Command="{Binding Path=MenuItem_Add}"></MenuItem> 
          <MenuItem Header ="Remove Node" Command="{Binding Path=RemoveCommand}"></MenuItem> 
          <MenuItem Header ="Edit Node" Command="{Binding Path=ProjMenuItem_Edit}" 
             CommandParameter="{Binding DestOrganTree, Path=Selected.OrganName}"></MenuItem> 
         </ContextMenu>       
        </local:ExtendedTreeView.ContextMenu> 

        <local:ExtendedTreeView.ItemTemplate> 
         <HierarchicalDataTemplate ItemsSource="{Binding SubOrganLocations}"> 
          <TextBlock Text="{Binding OrganName}" > 
          </TextBlock> 
         </HierarchicalDataTemplate> 
        </local:ExtendedTreeView.ItemTemplate> 
+0

是的,這也是對我的作品更好。但我期待在樹視圖的每個級別上都有不同的上下文項目。我不認爲這個解決方案可以解決這個問題...... #still_looking ... – CJBrew 2013-08-21 12:38:18

相關問題