Windows Phone 7 从代码中添加带有 itemtemplate 和 datatemplate 的列表框? [英] Windows Phone 7 add listbox with itemtemplate and datatemplate from code?
本文介绍了Windows Phone 7 从代码中添加带有 itemtemplate 和 datatemplate 的列表框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<ListBox x:Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10" >
<TextBlock Text="{Binding title}"/>
<TextBlock Text="{Binding Description}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
用源代码添加它的正确方法是什么?
What is the correct way to add this with source code?
已
试过这个:
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]
The property 'System.Windows.FrameworkTemplate.Template' is set more than once. [Line: 3 Position: 32]
为什么?
推荐答案
您可以简单地在 App.xaml 文件中的Resources"元素下定义共享模板.
You could simply define the shared template in your App.xaml file under the "Resources" element.
在 App.xaml 中定义:
Define it in 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
在您的用户界面中使用它:
Use it in your UI:
DataTemplate newTemplate = null;
string templateKey = "MySharedTemplate";
try { newTemplate = FindResource<DataTemplate>(this, templateKey); }
catch { newTemplate = null; }
if (newTemplate != null)
{
this.ListBox1.ItemTemplate = newTemplate;
}
这篇关于Windows Phone 7 从代码中添加带有 itemtemplate 和 datatemplate 的列表框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文