Clone Grid Windows Phone 8
本文关键字:Phone Windows Grid Clone | 更新日期: 2023-09-27 18:18:01
我有一个网格模板在XAML CODE:
<Grid x:name="gridTemplate>
Childrens...
</Grid>
现在我想把这个网格放在LongListSelector in foreach loop:
foreach(var item in myList)
{
clonedGrid= ??? (need clone here my xaml control)
longlistselector.Items.Add(clonedGrid):
}
这适用于我的WPF:
public static class ExtensionMethods
{
public static T XamlClone<T>(this T original)
where T : class
{
if (original == null)
return null;
object clone;
using (var stream = new MemoryStream())
{
XamlWriter.Save(original, stream);
stream.Seek(0, SeekOrigin.Begin);
clone = XamlReader.Load(stream);
}
if (clone is T)
return (T)clone;
else
return null;
}
}
如何在WINDOWS PHONE 8中实现此功能?
我会做一个contentControl,在那里我可以把dataTemplate从资源,像这样:
xaml
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="MyGrid">
<Grid>
<!-- here is your data template, where you can bind to item's properties -->
</Grid>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
cs foreach (var item in myList)
{
ContentControl control = new ContentControl();
control.Content = item;
control.ContentTemplate = Resources["MyGrid"] as DataTemplate;
longlistselector.Items.Add(control);
}
如果你的Grid没有很多属性设置,那么只需创建一个方法来创建新的Grid并将其作为参数传递给你的旧Grid,这样你就可以将所有属性设置为相同的。
public Grid CloneGrid(Grid input)
{
Grid temp = new Grid();
temp.Width = input.Widht;
... etc
return temp;
}
编辑:另一种方法是将属性定义为App.xaml
中的Style
,然后将其应用于Grid
:
Grid.Style = App.Current.Resources[StyleKey] as Style;