Windows Phone 7使用itemtemplate和datatemplate从代码添加列表框?

时间:2011-10-07 07:35:56

标签: windows-phone-7

<ListBox x:Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="10" >
                <TextBlock Text="{Binding title}"/>
                <TextBlock Text="{Binding Description}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

使用源代码添加此内容的正确方法是什么?

编辑:

尝试了这个:

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'设置了多次。 [线:3位置:32]

为什么?

1 个答案:

答案 0 :(得分:4)

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

在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

在您的界面中使用它:

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

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

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