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 8561881
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T16:36:16+00:00 2026-06-11T16:36:16+00:00

Download repro project Edit The solution working sometimes completely threw me off my initial

  • 0

Download repro project

Edit

The solution working sometimes completely threw me off my initial wondering why this is working in the first place. After all, the items aren’t part of the Visual tree. In the end, it makes total sense:

  • The buttons in that collection aren’t in the visual tree and thus element bindings don’t work.
  • Applying the templates puts them into the visual tree and binding, if applied at this time, start working.
  • This confirms the suspected race condition.

A colleague of mine did some extended debugging that showed the issue as well – in the cases the binding succeeded, OnApplyBinding was invoked first. So using the collection without adjusting the logical tree was simply flawed.

Thanks for the replies that put back on the right track!


Original Post

I have a view control that exposes an ObservableCollection, My view can contain arbitrary elements, e.g. buttons. Note the ElementName binding on the button:

<local:ViperView>    
    <local:ViperView.MenuItems>
        <Button Content="{Binding ElementName=btn, Path=Content}" />
    </local:ViperView.MenuItems>

    <Grid>
        <Button x:Name="btn" Content="HELLO WORLD" />
    </Grid>
</local:ViperView>

The control’s ControlTemplate just renders the content using an ItemsControl:

<ControlTemplate ...
...

    <ItemsControl
        x:Name="PART_NavigationMenuItemsHost"
        ItemsSource="{Binding MenuItems, RelativeSource={RelativeSource TemplatedParent}}" />
 </ControlTemplate>

The view above is assigned to the ActiveView property of my main view model. The main window just displays the view via data binding.

Now the problem: The ElementName binding within that view doesn’t work reliably if the view is not immediately assigned to the view model after it’s creation.

enter image description here

ElementName bindings work like this:

MainViewModel.ActiveView = new ViperView();

ElementName bindings works sometimes using normal priority:

var view = new ViperView();
Dispatcher.BeginInvoke(() => MainViewModel.ActiveView  view);

ElementName binding always fails if the view model property is set with low priority:

var view = new ViperView();
Dispatcher.BeginInvoke(DispatcherPriority.Render, () => MainViewModel.ActiveView = view);

ElementName binding sometimes works if the property is set from a worker thread (Binding engine marshalls back to the UI thread):

var view = new ViperView();
Task.Factory.StartNew(() => MainViewModel.ActiveView = view);

ElementName binding always fails if the worker thread has a delay:

var view = new ViperView();
var view = new ViperView();
Task.Factory.StartNew(() => 
{
    Thread.Sleep(100);
    MainViewModel.ActiveView = view;
});

I don’t have an answer to this. It appears to be related to timings. For example, if I add a short Thread.Sleep to the Task sample above, this always causes the bindings to break, while without the sleep, it only sometimes breaks.

This is quite the show stopper for me – any pointer are appreciated…

Thanks for your advice
Philipp

  • 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-11T16:36:17+00:00Added an answer on June 11, 2026 at 4:36 pm

    Given that the ElementName binding in part fails before the buttons in the sample are even added to the collection of the parent view, there’s not much I can do to intercept the bindings. A slightly dirty workaround would be to just refresh the bindings in those controls once the template has been applied and the visual tree established:

    Fron OnApplyTemplate, invoke:

    internal static class BindingUtil
    {
        /// <summary>
        /// Recursively resets all ElementName bindings on the submitted object
        /// and its children.
        /// </summary>
        public static void ResetElementNameBindings(this DependencyObject obj)
        {
            IEnumerable boundProperties = obj.GetDataBoundProperties();
            foreach (DependencyProperty dp in boundProperties)
            {
                Binding binding = BindingOperations.GetBinding(obj, dp);
                if (binding != null && !String.IsNullOrEmpty(binding.ElementName)) //binding itself should never be null, but anyway
                {
                    //just updating source and/or target doesn’t do the trick – reset the binding
                    BindingOperations.ClearBinding(obj, dp);
                    BindingOperations.SetBinding(obj, dp, binding);
                }
            }
    
            int count = VisualTreeHelper.GetChildrenCount(obj);
            for (int i = 0; i < count; i++)
            {
                //process child items recursively
                DependencyObject childObject = VisualTreeHelper.GetChild(obj, i);
                ResetElementNameBindings(childObject);
            }
        }
    
    
        public static IEnumerable GetDataBoundProperties(this DependencyObject element)
        {
            LocalValueEnumerator lve = element.GetLocalValueEnumerator();
    
            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;
                if (BindingOperations.IsDataBound(element, entry.Property))
                {
                    yield return entry.Property;
                }
            }
        }
    }
    

    Another fix, and probably preferable, would be to change the logical tree at runtime. Adding the code below to my view solves the issue, too:

    public class ViperView : ContentControl
    {
        private readonly ObservableCollection<object> menuItems = new ObservableCollection<object>();
    
        public ObservableCollection<object> NavigationMenuItems
        {
            get { return menuItems; }
        }
    
    
        public ViperView()
        {
            NavigationMenuItems.CollectionChanged += OnMenuItemsChanged;
        }
    
        private void OnMenuItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (var newItem in e.NewItems)
                {
                    AddLogicalChild(newItem);
                }
            }
        }
    
        protected override IEnumerator LogicalChildren
        {
            get
            {
                yield return this.Content;
                foreach (var mi in NavigationMenuItems)
                {
                    yield return mi;
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I download a png file from link. But sometimes there is no file. And
I am working on a project that uses Maven as the build tool. I
I logged the issue with Microsoft here - the Repro is available for download:
this post ideally continues my other post on MEF plugins, but my first post
Their is a project I would like to start working on but the problem
I have forked a project on GitHub and I want to download only the
Essentially I'm looking to use git as a download command. I have a project
Steps to Repro: Make a C# project in VS 2010 Professional on Windows 7
I want to start using GitHub Pages for my project's website. This simply requires
I want to download this open source application, and they are using Git. What

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.