2

我正在使用Visifire图表在 Windows Phone 7 应用程序上显示数据。我创建了一个正确绑定到依赖属性的图表。效果很好。我决定将图表制作成用户控件,因为我打算在另一个项目中使用它以及相同的设置。现在我的数据绑定不起作用,除非我将它绑定在后面的代码中而不是 XAML 中。

这就是我所拥有的:

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

以及背后的代码:

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();
}

如果我取消注释该行theChart.Series[0].DataSource = Results;,它将完美运行。但是,如果我将该行注释掉(就像我在将图表移动到 UserControl 之前所做的那样),它就不会绑定。(顺便说一句:theChartx:name图表的父级。所以第一个元素.Series[0],,,对图表的引用)。

有谁知道为什么会发生这种情况?再次,它工作得很好,直到我将代码移动到 UserControl。

谢谢

4

1 回答 1

2

如果我对您的理解正确,您已经创建了这个 UserControl,以便您可以将它的实例放入应用程序的各个页面中。

在这种情况下,您可能会为这些实例命名。该名称将替换最初在 UserControl 的 Xaml 中分配的名称“Root”。因此,绑定ElementName=Root将失败。

通常有一个名为“LayoutRoot”的根元素(通常是 Grid)。因此,不要依赖可以更改的 UserControl 名称,而是使用“LayoutRoot”,按照惯例,它是 UserControl 的 Content 元素。像这样:-

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

请注意,属性路径现在从Parent它开始,您UserControl无需知道 UserControl 的名称。

于 2010-04-20T21:06:55.033 回答