I have a window with a simple frame element within it (we’ll call it “myFrame”). Within the Window.Loaded I am parsing a string variable (loaded from an external source) with XamlReader.Parse(string) and the result is a Page object (local var is called “myPage”). I’m setting myFrame.Content = myPage.
Inside of the page is a label, like so:
<label Name="DataBindingTestLabel" Content="{Binding Path=TestLabel, TargetNullValue='Null value'}" />
I am trying to provide an anonymous type (for easy testing) as the frame’s datacontext, like:
this.ContentFrame.DataContext = new { TestLabel = "Hello, world." };
I have verified that the DataContext property has the value after it’s set and keeps the value for as long as I can step through the window’s execution, but the value is lost sometime before the window is rendered and the fallback value, “Null value,” is displayed.
After enabling databinding tracing, the output window in visual studio shows:
System.Windows.Data Information: 41 : BindingExpression path error: ‘TestLabel’ property not found for ‘object’ because data item is null. This could happen because the data provider has not produced any data yet. BindingExpression:Path=TestLabel; DataItem=null; target element is ‘Label’ (Name=’DataBindingTestLabel’); target property is ‘Content’ (type ‘Object’)
Any insight into something I’m doing wrong is most appreciated.
As it turns out, the frame element has issues dealing with data context while the content is a page element.
The solution was to use a more generic element (ContentControl) and instead of having the dynamic content be a Page element, we are using UserControl elements. In this setup, datacontext is not lost and binding works as expected.