views:

74

answers:

1

I am using the Visifire charts to display data on a Windows Phone 7 application. I created a chart that was properly bound to a dependency property. It worked great. I decided to make the chart into a user control, since I was going to use it in another project as well with the same setup. Now my databinding doesn't work unless I bind it in the code behind rather than in the XAML.

here's what I have:

<UserControl ... x:Name="root">
 ...
     <chart:DataSeries ... DataSource="{Binding ElementName=root, Path=Results}">
 ...
</UserControl>

and the code behind:

public MyList Results
{
    get { return (MyList)GetValue(ResultsProperty); }
    set { SetValue(ResultsProperty, value); }
}

    // Using a DependencyProperty as the backing store for Results.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ResultsProperty =
        DependencyProperty.Register("Results", typeof(MyList), typeof(MyChart), new PropertyMetadata(null));


public GoogleChart()
{
    Loaded += delegate
    {
    //  theChart.Series[0].DataSource = Results;
    };
    Results = new GoogleResults();
    InitializeComponent();
}

If I uncomment the line theChart.Series[0].DataSource = Results; it works perfectly. But if I leave that line commented (like I had before I moved the chart to the UserControl) it doesn't bind. (By the way: theChart is the x:name of the parent of the chart. So the first element, .Series[0], references to the chart).

Does anyone know why this would happen? Again, it worked great until I moved the code to a UserControl.

Thanks

+2  A: 

If I'm understanding you correctly you've created this UserControl so that you can place instances of it into various pages in your app.

In that case you are likely to be giving those instances a name. That name will replace the name "Root" that is initially assigned in the UserControl's Xaml. Hence the binding for ElementName=Root will fail.

Typically there is a root element (normally a Grid) with the name "LayoutRoot". Hence instead of relying on the UserControl name which can change use "LayoutRoot" which by convention is the Content element for the UserControl. Like so:-

<chart:DataSeries ... DataSource="{Binding ElementName=LayoutRoot, Path=Parent.Results}">

Note the property path now starts with Parent which takes you up to the UserControl without actually needing to know the UserControl's name.

AnthonyWJones
Awesome. I did not know that changing the x:Name from another class changes the name everywhere. That's good to know. That's a nice tip you gave me there. I think it just might be handy more often than just this once. Thanks.
Joel