user610650
user610650

Reputation:

Binding MenuItem Visibility to Visibility of the preceding MenuItem

I want to bind mnuAddLessonAfter's visibility to that of mnuAddLessonBefore. I can't seem to make it work, ie setting mnuAddLessonBefore's visibility to collapsed only hides mnuAddLessonBefore, not mnuAddLessonAfter. What am I doing wrong?

<TreeView Grid.Column="0"
          HorizontalAlignment="Stretch"
          Name="treeViewLesson"
          VerticalAlignment="Stretch"
          SelectedItemChanged="treeViewLesson_SelectedItemChanged"
          PreviewMouseLeftButtonDown="treeViewLesson_PreviewMouseLeftButtonDown"
          AllowDrop="True"
          Drop="treeViewLesson_Drop"
          MouseMove="treeViewLesson_MouseMove"
          DragEnter="treeViewLesson_DragEnter">

<TreeView.ContextMenu>

  <ContextMenu Name="context_menu_lesson">

    <MenuItem Name="mnuAddLesson"
              Header="Add lesson"
              Click="mnuAddLesson_Click" />

    <MenuItem Name="mnuAddLessonBefore"
              Header="Add lesson before"
              Click="mnuAddLessonBefore_Click" />

    <MenuItem Name="mnuAddLessonAfter"
              Header="Add lesson after"
              Click="mnuAddLessonAfter_Click"
              Visibility="{Binding ElementName=mnuAddLessonBefore, Path=Visibility}" />

EDIT:

I noticed this in the Output console:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=mnuAddLessonBefore'. BindingExpression:Path=Visibility; DataItem=null; target element is 'MenuItem' (Name='mnuAddLessonAfter'); target property is 'Visibility' (type 'Visibility')

Upvotes: 2

Views: 629

Answers (1)

biju
biju

Reputation: 18000

Context menus are tricky to bind against. They exist outside the visual tree of your control, hence they can't find your element name.

Try This workaround

 public Window1()
  {
    InitializeComponent();
    NameScope.SetNameScope(context_menu_lesson, NameScope.GetNameScope(this));
  } 

Upvotes: 1

Related Questions