2011-10-07 75 views
1
<ListBox x:Name="listBox"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Margin="10" > 
       <TextBlock Text="{Binding title}"/> 
       <TextBlock Text="{Binding Description}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

什么是正确的方式添加此源代码?Windows Phone 7从代码添加itemtemplate和datatemplate的列表框?

编辑:

尝试这样做:

public static DataTemplate createDataTemplate() 
{ 
    return (DataTemplate)System.Windows.Markup.XamlReader.Load(
     @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> 
      <TextBlock Text=""{Binding Title}"" /> 
      <TextBlock Text=""{Binding Description}"" /> 
      <Image Source=""{Binding Image}"" /> 
     </DataTemplate>" 
    ); 
} 

当我把这个:

for (int i=0; i<10; i++) { 
       ListBox lb  = new ListBox(); 
       lb.ItemTemplate = createDataTemplate(); 
       //...then add to a pivotitem 
} 

我得到这个:

属性“System.Windows.FrameworkTemplate .Template'被设置多次。 [Line:3 Position:32]

为什么?

+0

(请参见时使用大写我的你自己而不是一些变量,也请用大写字母开始句子,谢谢!) – Arjan

回答

4

您只需在“Resources”元素下的App.xaml文件中定义共享模板即可。

在App.xaml中定义它:

<DataTemplate x:Key="MySharedTemplate"> 
    <StackPanel Margin="10" > 
     <TextBlock Text="{Binding title}"/> 
     <TextBlock Text="{Binding Description}"/> 
    </StackPanel> 
</DataTemplate> 

访问它的代码:

#region FindResource 
/// <summary>Get a template by the type name of the data.</summary> 
/// <typeparam name="T">The template type.</typeparam> 
/// <param name="initial">The source element.</param> 
/// <param name="type">The data type.</param> 
/// <returns>The resource as the type, or null.</returns> 
private static T FindResource<T>(DependencyObject initial, string key) where T : DependencyObject 
{ 
    DependencyObject current = initial; 

    if (Application.Current.Resources.Contains(key)) 
    { 
     return (T)Application.Current.Resources[key]; 
    } 

    while (current != null) 
    { 
     if (current is FrameworkElement) 
     { 
      if ((current as FrameworkElement).Resources.Contains(key)) 
      { 
       return (T)(current as FrameworkElement).Resources[key]; 
      } 
     } 

     current = VisualTreeHelper.GetParent(current); 
    } 

    return default(T); 
} 
#endregion FindResource 

用它在你的UI:

DataTemplate newTemplate = null; 
string templateKey = "MySharedTemplate"; 

try { newTemplate = FindResource<DataTemplate>(this, templateKey); } 
catch { newTemplate = null; } 

if (newTemplate != null) 
{ 
    this.ListBox1.ItemTemplate = newTemplate; 
} 
+0

我有一个关键点,并有很多pi投票反对。每个pivotitem都有一个列表框,这就是为什么我需要添加代码这一行。我可以做什么替代方案?在我的xaml文件中目前没有任何模板... – lacas