简体   繁体   中英

Datacontext lost with dynamic xaml in WPF

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.

I hope someone else can confirm this, since I've only been using anonymous types myself very recently, but the MSDN article on anonymous types seems to indicate that, as I suspected, your anonymous type is simply going out of scope. In the Remarks section of the page linked above, it says "An anonymous type has method scope," so I'm inclined to believe that's your problem.

Again, I'm not entirely sure, just thought I'd offer my thoughts on the matter...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM