I create a Silverlight Chart, with the Silverlight 4 toolkit, the April release.
Consider the following chart:
<Grid x:Name="LayoutRoot" Background="White">
<Charting:Chart Title="Chart to test" Name="MySuperChart">
<Charting:LineSeries x:Name="MyLineSeries" Title="Something" />
</Charting:Chart>
</Grid>
So far so good. I can access the Series in the chart by MySuperChart.Series[0] But when I try to reference MyLineSeries, it appears to be null.

This is an interesting little gotcha. It helps if you look a bit under the hood at how the variable
MyLineSeriesis created and assigned. Navigate to the definition of theInitializeComponentmethod. You will end up at the MainPage.g.cs generated file. It will contain this field:-and in the
InitializeComponentyou will find this line:-So on the surface of it by the time the call to
InitializeComponentin your constructor has completed theMyLineSeriesshould have been assigned a value. However as you can see its still null, hence it can be concluded thatFindName("MyLineSeries")failed to find the series. So the question is why did it fail?Why Doesn’t FindName Work?
FindNamesearches what is refered to in the documentation as the “object tree”, looking for an object that has the name specified (there are added complications of what are known as namescopes but that is not at play here). Typically objects end up in the “object tree” through common base types likePanelorContentControlwhich have propeties such asChildrenandChildrespectively. These properties are specified in theContentPropertyattribute on the classes which allows for the UI structure to be described more naturally. E.g.:-Instead of
The
Chartcontrol, on the other hand, is not a simplePanelderivative and has a lot more work to do to build its UI. In the case of theCharttheContentPropertyAttributespecifies theSeriescollection parameter. This allows your more natural Xaml:-However because
Charthas a lot of extra work in order do determine what exactly should be in the “object tree” that will represent its final UI the series collection items don’t immediately become part of the “object tree”. As result theFindNamein theInitializeComponentsimply doesn’t find them.Work Around – Option 1
You could use your knowledge of the ordinal position of “MyLineSeries” in the chart to handle the assignment of a
MyLineSeriesvariable in the constructor. Remove thex:Name="MyLineSeries"from the Xaml then in code:-Work Around – Option 2
You could wait until the series is available in the “object tree” which is true once the containing
UserControlhas fired itsLoadedevent:-