2013-03-30 88 views
0

我一直在試圖通過使用Panorama.TitleTemplate屬性和一個字典綁定數據到它沒有任何成功自定義我的全景頁面的標題區域。我的XAML代碼如下:將數據綁定到Panorama.TitleTemplate

<Grid x:Name="LayoutRoot"> 
    <controls:Panorama Name="siteHubPanoramaControl"> 
     <controls:Panorama.TitleTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal" Height="75" Margin="0,75,0,0" Width="470" DataContext="{Binding}"> 
        <Image Source="{Binding imageSource}" /> 
        <TextBlock Text="{Binding name}" /> 
       </StackPanel> 
      </DataTemplate> 
     </controls:Panorama.TitleTemplate> 

     <!--Panorama item one--> 
     <controls:PanoramaItem Header="Site Info"> 
      <Grid/> 
     </controls:PanoramaItem> 

     <!--Panorama item two--> 
     <controls:PanoramaItem Header="Others"> 
      <Grid/> 
     </controls:PanoramaItem> 
    </controls:Panorama> 
</Grid> 

我用下面的代碼字典綁定到數據模板:

Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
dictionary.Add("name", this.name); 
dictionary.Add("imageSource", "http://..."); 

siteHubPanoramaControl.DataContext = dictionary; 

我一直在尋找一個解決方案,但沒能找到。 如果你能幫助我解決這個問題,我會很高興。

也有一個很好的資料來了解數據綁定?

在此先感謝...

回答

1

兩個nameimageSource不是財產。這只是你的字典中的關鍵。所以,當你試圖綁定這兩個名稱時,它找不到任何屬性。

您必須將這些值公開到屬性中。例如,

public string Name 
{ 
    get { return dictionary["name"]; } 
} 

我不確定任何其他方式,但這將是我的想法。它應該工作我認爲。

編輯:

好吧,假設你使用的MVVM模式,這下面的代碼應該工作。

視圖模型

public class MainPageViewModel 
    { 
     private Dictionary<string,string> _dictionary = new Dictionary<string, string>(); 

     public MainPageViewModel() 
     { 
      _dictionary.Add("name", "Foo"); 
      _dictionary.Add("imageSource", "http://"); 
     } 

     public string Name 
     { 
      get { return _dictionary["name"]; } 
     } 

     public string ImageSource 
     { 
      get { return _dictionary["imageSource"]; } 
     } 
    } 

代碼隱藏

public partial class MainPage : PhoneApplicationPage 
{ 
    private MainPageViewModel _vm; 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 

     _vm = new MainPageViewModel(); 
     DataContext = _vm; 
    } 
} 

XAML

<Grid x:Name="LayoutRoot"> 
    <phone:Panorama Name="siteHubPanoramaControl"> 
     <phone:Panorama.Title> 
      <StackPanel Orientation="Horizontal"> 
        <Image Source="{Binding ImageSource}"/> 
        <TextBlock Text="{Binding Name}" /> 
       </StackPanel> 
     </phone:Panorama.Title> 
     <!--Panorama item one--> 
     <phone:PanoramaItem Header="Foo"> 
      <Grid/> 
     </phone:PanoramaItem> 

     <!--Panorama item two--> 
     <phone:PanoramaItem Header="Others"> 
      <Grid/> 
     </phone:PanoramaItem> 
    </phone:Panorama> 
</Grid> 

對於XAML,而是採用Panorama.TitleTemplate和應用DataTemplate,使用Panorama.Title代替,這使得它更容易。我試着用TitleTemplate,我只能使它能夠綁定標題而不是圖像。所以最簡單的解決方法是使用Panorama.Title

+0

我寧願硬編碼XAML中的兩個項目的值,因爲綁定是微不足道的,除非您經常更改您的應用程序標題和圖像,或者您將其用於其他目的。 –

+0

該解決方案適用於我。謝謝你的幫助。 –

+1

謝謝Shulhi,對這個問題的很多答案都使用DataTemplate。顯然,他們不驗證代碼的工作原理,因爲它不起作用。這是一個完美的解決方案。 – Seamus