我想通過命令參數在我的視圖後面的代碼中的依賴屬性發送由dp設置的屬性給我的viewmodel(通過datacontext綁定)。該屬性(ParentUserControl)似乎在進入時正確初始化,但是我似乎無法發送它。我已經試過下面代碼隱藏的綁定依賴屬性到CommandParameter
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyView}}}" />
</ContextMenu>
</DataGrid.ContextMenu>
和
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />
</ContextMenu>
兩個綁定我使用mvvmlight中繼命令如下所示然而在該方法中測試pased()的參數總是空
CommandTest = new RelayCommand<object>(x => test(x));
這是視圖後面的代碼中附加的依賴項屬性:
public static readonly DependencyProperty ParentUserControlProperty = DependencyProperty.Register(
"ParentUserControl", typeof(UserControl), typeof(MyView), new PropertyMetadata(default(UserControl)));
public UserControl ParentUserControl
{
get { return (UserControl) GetValue(ParentUserControlProperty); }
set { SetValue(ParentUserControlProperty, value); }
}
'ContextMenu'打破了視覺樹,你可以用'PlacementTarget'來解決這個問題,就像[這裏]解釋的一樣(http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or -上下文菜單)。 – bab7lon
我不確定這是我在找什麼,命令已經綁定到viewmodel並且工作正常,它的命令參數我遇到了困難 –
儘管我在CommandParameter上嘗試了它,但沒有運氣。 –