3 回答

TA貢獻1817條經驗 獲得超6個贊
如下所示:
PlacementTarget是擁有ContextMenu的控件(例如:DataGrid)。不需要“標簽”屬性。
IsEnabled綁定到DataGrid的“ myProperty”值。
我對此進行了測試,并且可以正常工作。綁定存在類似問題。
<ContextMenu
DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}"
IsEnabled="{Binding myProperty}"
>

TA貢獻1744條經驗 獲得超4個贊
因為ContextMenu不在可視樹中,所以綁定將不起作用。一個簡單的解決方案是使用代理模式,你可以創建一個繼承的包裝類DependencyObject,并具有DependencyProperty將保持DataContext你的Window,那么你可以在XAML代理的資源,最后你的綁定MenuItem通過代理命令添加到您所需的命令賓語。
樣本代理:
Public class ProxyClass : DependencyObject
{
Public object Data {get; set;}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("DataProperty", typeof(object), typeof(ProxyClass), new FrameworkPropertyMetadata(null));
}
如何在XAML中使用:
<Window DataContext="{Binding MyViewModel}">
...
<Window.Resources>
<ProxyClass Data={Binding} x:Key="BindingProxy"/>
</Window.Resources>
...
<MenuItem Command="{Binding Source={StaticResource BindingProxy}, Path=Data.MyDesiredCommand"/>
...
</Window>
怎么了?
Data財產ProxyClass將綁定到DataContext的Window,那么它所有的comamnds和你的屬性ViewModel的內部ProxyClass資源。
這種方法的另一個好處是可移植性,并且可以在多個視圖和項目中重復使用。
添加回答
舉報