我有一個列表框,我爲其設計ItemContainer以包含上下文菜單。這是同樣的xaml。「Caliburn Message.Attach()拋出的方法沒有找到任何目標」
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
...
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Remove Group" cal:Message.Attach="DeleteGroup"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
我已經編碼了ViewModel中的目標方法,如下所示。
public void DeleteGroup() { //ToDo
...
}
ViewModel被設置爲其中存在ListBox的UserControl的DataContext。
以上代碼結果爲「沒有找到方法的目標」。我不知道爲什麼這不起作用。我也嘗試了以下變體
<MenuItem Header="Remove Group" cal:Message.Attach="DeleteGroup"
cal:Action.Target="{Binding ElementName=UCRelayDispositionView, Path=DataContext}">
其中UCRelayDispositionView是UserControl的名稱。
爲什麼上面的代碼不起作用?
編輯:1 也試過以下
<MenuItem Header="Remove Group" cal:Message.Attach="DeleteGroup"
cal:Action.TargetWithoutContext="{Binding ElementName=UCRelayDispositionView, Path=DataContext}">
這
<MenuItem Header="Remove Group" cal:Message.Attach="DeleteGroup"
cal:Action.TargetWithoutContext="{Binding ElementName=UCRelayDispositionView}">
編輯:2 我曾嘗試使用標籤在ItemContainer以下方式,但它也不起作用。
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Tag" Value="{Binding Path=DataContext, ElementName=UCRelayDispositionView}"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Remove Group"
cal:Message.Attach="DeleteGroup()"
cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>
</ContextMenu>
</Setter.Value>
</Style>
</ListBox.ItemContainerStyle>
編輯3:綁定錯誤
System.Windows.Data Error: 40 : BindingExpression path error: 'PlacementTarget' property not found on 'object' ''MenuItem' (Name='')'. BindingExpression:Path=PlacementTarget.Tag; DataItem='MenuItem' (Name=''); target element is 'MenuItem' (Name=''); target property is 'TargetWithoutContext' (type 'Object')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=UCRelayDispositionView'. BindingExpression:Path=DataContext; DataItem=null; target element is 'ContextMenu' (Name=''); target property is 'Tag' (type 'Object')
您的代碼不起作用。仍然給出相同的錯誤。就使用標籤而言,我在哪裏放置它?我在ItemContainerStyle上有這個上下文菜單! – Jatin
如果你看看我發佈的SO鏈接,有一個例子可以說明。基本上你必須使用'ContextMenu.PlacementTarget'屬性來獲取產生上下文菜單的項並綁定到它的'DataContext',儘管它可能需要你將父容器的'DataContext'轉換爲'Tag'屬性。這對我很有用(可能值得在視圖中創建一個事件,這樣您可以在單擊菜單項時進入代碼隱藏和調試,這樣您可以瀏覽對象圖並發現正確的綁定路徑) – Charleh
我編輯了標記爲** EDIT 2 **的問題。我不確定我們是否可以使用Style來設置標籤,但是仍然存在相同的錯誤。 – Jatin