Windows Phone 7 добавить список с шаблонами элементов и датами из кода? - PullRequest
1 голос
/ 07 октября 2011
<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 Ответ

4 голосов
/ 07 октября 2011

Вы можете просто определить общий шаблон в файле 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

Используйте его в своем интерфейсе:

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

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

if (newTemplate != null)
{
    this.ListBox1.ItemTemplate = newTemplate;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...