Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8104389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:49:30+00:00 2026-06-05T23:49:30+00:00

I have a DataTemplate within my Window’s Resources section that creates a TextBlock with

  • 0

I have a DataTemplate within my Window’s Resources section that creates a TextBlock with a ContextMenu. I want to be able to set whether a MenuItem within the ContextMenu is visible from within my Window’s view model. I have tried accessing the DataContext of the Window by setting ElementName, and also tried setting RelativeSource, but both approaches resulted in binding errors. I’m not sure what else I can try.

I have created a small example that shows what I’m trying to do:

XAML:

<Window x:Class="DataTemplateTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">


<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="TestDataTemplate">
            <TextBlock Text="{Binding}">
                <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Test" Visibility="{Binding Path=DataContext.MenuItemVisible, ElementName=Root}"/>
                    </ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>

<ScrollViewer x:Name="Root">
    <ItemsControl ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource TestDataTemplate}" />
</ScrollViewer>

Code behind:

using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;

namespace DataTemplateTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        protected readonly MainWindowViewModel vm;

        public MainWindow()
        {
            InitializeComponent();
            vm = new MainWindowViewModel();
            DataContext = vm;
        }
    }

    public class MainWindowViewModel : INotifyPropertyChanged
    {
        private Visibility menuItemVisible = Visibility.Hidden;
        public Visibility MenuItemVisible { get { return menuItemVisible; } set { menuItemVisible = value; NotifyPropertyChanged("MenuItemVisible"); } }

        public List<string> Items { get; set; }

        public MainWindowViewModel()
        {
            Items = new List<string>() { "Alpha", "Beta", "Gamma" };
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

The error I get is

System.Windows.Data Error: 4 : Cannot find source for binding with reference ‘ElementName=Root’.
BindingExpression:Path=DataContext.MenuItemVisible; DataItem=null;
target element is ‘MenuItem’ (Name=”); target property is
‘Visibility’ (type ‘Visibility’)

When I set RelativeSource instead of ElementName in the binding:

RelativeSource={RelativeSource Mode=FindAncestor, 
                AncestorType={x:Type ScrollViewer}}

I get the following error:

System.Windows.Data Error: 4 : Cannot find source for binding with
reference ‘RelativeSource FindAncestor,
AncestorType=’System.Windows.Controls.ScrollViewer’,
AncestorLevel=’1”.
BindingExpression:Path=DataContext.MenuItemVisible; DataItem=null;
target element is ‘MenuItem’ (Name=”); target property is
‘Visibility’ (type ‘Visibility’)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:49:32+00:00Added an answer on June 5, 2026 at 11:49 pm

    I have found the answer here:

    So all I had to do to access the window’s DataContext was set:

    Source={x:Reference Name=Root}
    

    An explanation of why ElementName does not work in this case is found here. Specifically:

    Probably the simplest example of where we don’t have inheritance context links is across > random property elements:

    <Button>
      <Button.ContextMenu>
        <ContextMenu/>
      </Button.ContextMenu>
    </Button>
    

    ContextMenu is neither a visual nor logical child of Button, nor is it one of the inheritance context cases listed above (ContextMenu is not a Freezable).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have ItemsControl with DataTemplate that looks like this: I want to achieve effect
I have declared a DataTemplate in Window.Resources; I don't intend to use it inside
I have a textblock within a GridView that is bound to a property that
I've got a ListBox, within it I have a custom DataTemplate that builds a
hello everybody i have a listbox within which is a datatemplate.Inside it is checkbox,textbox,label...Wat
I have a DataTemplate that is used by a listbox: <local:BooleanToFontColorConverter x:Key=boolToFontColor /> <DataTemplate
I have a DataTemplate containing an Image. To the Image I added a ContextMenu
I have the following DataTemplate : <DataTemplate x:Key=ColoringLabels> <TextBlock Padding=0 Margin=0 Name=Username Text={Binding Username}
In my MainWindow.xaml, I have the following reference to a ResourceDictionary: <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries>
I have various user controls that get placed in a content control within my

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.