ContextMenuItem isEnabled绑定到Object属性

时间:2017-07-21 07:14:28

标签: c# wpf data-binding contextmenu

我在树视图中声明了TreeView项的ContextMenu:

<TreeView  ItemsSource="{Binding countries, Mode=TwoWay}" SelectedItemChanged="TreeView_SelectedItemChanged">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type myapp:City}"  ItemsSource="{Binding Cities}">
            <StackPanel Orientation="Horizontal" ContextMenu="{StaticResource CityItem}">
                <TextBlock Text="{Binding CityName}" FontSize="14" Foreground="Bisque"/>
                ...

ContextMenu本身声明为:

<ContextMenu x:Key ="CityItem"  StaysOpen="true" Foreground="Bisque">
    <MenuItem Header="Edit City"  CommandParameter="{Binding Parent, RelativeSource={RelativeSource Self}}" Click="EditCityClick"/>
    <MenuItem Header="DeleteCity" CommandParameter="{Binding Parent, RelativeSource={RelativeSource Self}}" Click="DeleteCityClick"/>
</ContextMenu>

嗯,此时一切正常

private void DeleteCityClick(object sender, RoutedEventArgs e)
{
    City city = ((FrameworkElement)e.OriginalSource).DataContext as City;
        ...
}

我可以访问城市对象,修改,删除,根据城市和城市属性的变化,在gui中更新所有内容(onpropertychanged工作正常)。

问题是如何禁用将ContextMenuItem绑定到City对象属性的IsEnabled?让我们说

public bool IsEnabled { get; set;}

我尝试了几种方法,但是如何从ContextMenu MenuItem访问源对象(City)。

谢谢!

编辑:抱歉打字错误但是:

public string IsEnabled { get; set;}

实际上是:

public bool IsEnabled { get; set;}

编辑2:

有趣&#34;不是wpf ...&#34;

enter image description here

2 个答案:

答案 0 :(得分:2)

我认为你的问题是,ContextMenu在资源中。因此,您可以使用PlacementTarget来绑定它。

<ContextMenu x:Key ="CityItem" IsEnabled="{Binding PlacementTarget.DataContext.IsEnabled, RelativeSource={RelativeSource Self}}">

答案 1 :(得分:2)

试试这个:

<MenuItem ... IsEnabled="{Binding PlacementTarget.DataContext.IsEnabled, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />

它绑定到父DataContext PlacementTarget的{​​{1}},ContextMenu应该是City对象。