2010-04-20 103 views
2

我正在使用Visifire圖表在Windows Phone 7應用程序上顯示數據。 我創建了正確綁定到依賴項屬性的圖表。它效果很好。我決定將圖表製作成用戶控件,因爲我打算在另一個項目中使用它,並且使用相同的設置。現在我的數據綁定不起作用,除非我將它綁定在後面的代碼而不是XAML中。Silverlight:奇怪的數據綁定問題

這裏就是我有:

<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之前那樣),它就不會綁定。 (順便說一下:theChart是圖表父項的x:name,所以第一個元素.Series[0]引用了圖表)。

有誰知道爲什麼會發生這種情況?再次,它工作得很好,直到我將代碼移到UserControl。

感謝

回答

2

如果我理解你正確地你已經創造了這個用戶控件,這樣你可以把它的實例到您的應用程序不同的頁面。

在這種情況下,您可能會給這些實例一個名稱。該名稱將替換最初在UserControl的Xaml中分配的名稱「Root」。因此,ElementName=Root的綁定將失敗。

通常有一個名爲「LayoutRoot」的根元素(通常是一個Grid)。因此,而不是依靠UserControl名稱可以更改使用「LayoutRoot」,按照慣例是UserControl的內容元素。像這樣: -

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

注意屬性路徑現在開始與Parent這需要你到UserControl而無需實際需要知道用戶控件的名字。

+0

太棒了。我不知道從其他類更改x:Name會改變名稱。這很好。這是你給我的一個很好的建議。我認爲它可能會比以往更方便。謝謝。 – Joel 2010-04-21 19:57:44