2017-06-30 57 views
1

我有一個WPF綁定問題,我找不出來。我有一個格式化爲一個顯示文本菜單模板:WPF上下文菜單不會綁定到VIewModel屬性

<ContextMenu x:Key="CopyPasteContextMenu"> 
    <MenuItem Header="AlternateDelete" 
       Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
       RelativeSource={RelativeSource Self}, Mode=OneWay}"/> 
</ContextMenu> 

上下文菜單中DataTemplat被使用,以及邊境上的標籤是否正確找到PropertyEditorView的結合,我只是無法得到它從邊界到背景菜單。

<DataTemplate x:Key="PropertyValueCellViewingTemplate" DataType="viewModels:IConfigurationItemViewModel"> 
    <Border x:Name="ValueCellBorder" 
      Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type views:PropertyEditorView}}}" 
      ContextMenu="{StaticResource CopyPasteContextMenu}" 
      Style="{StaticResource PropertyGridValueCellBorderStyle}"> 
     (...) 
    </Border> 
</DataTemplate> 

標記可以正確地綁定到我的視圖模型,它被稱爲「PropertyEditorViewModel」。我可以在視覺樹中調試系統時看到這一點。當我鑽入我的上下文菜單時,綁定不會正常發生。

對於我的命令工作,我需要它正確地綁定到命令PropertyEditorView視圖模型命令稱爲「AlternateDeleteCommand」。

public class PropertyEditorViewModel : DisposableViewModelBase, IPropertyEditorViewModel 
{ 
    public ICommand AlternateDeleteCommand { get; set; } 

搜索這一天爲止,不知道爲什麼我綁定不正常的上下文菜單上,人有我丟失的東西?

謝謝!

+0

我只是做了一個快速測試,並發現的MenuItems被繼承的上下文菜單的對象的DataContext的 - 例如,我希望,如果'PropertyEditorViewModel'是DataTemplate中的DataContext的,因此,如果DataTemplate中的Border,那麼在MenuItem中,Command =「{Binding AlternateDeleteCommand}」將起作用。 –

+0

如果不確定綁定是(或似乎是)失敗的原因,請始終爲其添加「PresentationTraceSources.TraceLevel = High」。當綁定更新時,這會在運行時禁止很多行調試信息到VS輸出窗格。它會告訴你到底它在做什麼來查找它的源屬性,如果失敗,它會告訴你在哪裏以及爲什麼。 –

+0

我確實嘗試了JM下面提出的建議,並且它能夠工作,所以我將它移回到數據模板中,並且在將相對源設置爲上下文菜單後仍然有效。謝謝埃德! –

回答

0

相對來源不需要在上下文菜單上而不是在菜單項上?由於您正在檢查上下文菜單的放置目標?

<MenuItem Header="AlternateDelete" 
      Command="{Binding Path=PlacementTarget.Tag.DataContext.AlternateDeleteCommand, 
      RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Mode=OneWay}" /> 
+0

感謝,似乎工作! –

相關問題