我試圖將命令綁定到WPF中的菜單項。我使用的是與我所有其他命令綁定相同的方法,但我無法弄清楚爲什麼它不起作用。MVVM綁定命令上下文菜單項
我目前正在結合我的命令是這樣的:
Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MyCommand}"
這是它出錯(這是一個用戶控件內)
<Button Height="40" Margin="0,2,0,0" CommandParameter="{Binding Name}"
Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ConnectCommand}">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" CommandParameter="{Binding Name}"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.RemoveCommand}"/>
</ContextMenu>
</Button.ContextMenu>
...
第一個命令綁定像它應該工作,但第二個拒絕做任何事情。 我試過改變祖先級別,並命名我的控制通過ElementName而不是RelativeSource來訪問它,但仍然沒有改變。它一直說「無法找到綁定參考源...」
我錯過了什麼?
我不得不去檢查,但菜單項可以在不同的樹,所以它無法找到用戶控件,因爲在技術上它是不是一個祖先(史努比可以證實我是否記得這個權利)。對於其他命令綁定(例如Button控件的命令),爲什麼不能只執行Command =「{Binding Path = ConnectCommand}」? Button應該繼承UserControl的DataContext,因此不需要使用整個RelativeSource/FindAncestor語法。 – MetalMikester 2012-04-03 13:31:35