我在XAML CODE中有一个网格模板:
<Grid x:name="gridTemplate>
Childrens...
</Grid>
现在我想在 foreach 循环中将此网格放在 LongListSelector 中:
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中实现此功能?
答案 0 :(得分:0)
我会创建一个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);
}
答案 1 :(得分:-1)
如果Grid没有设置很多属性,那么只需创建创建新Grid的方法并将其作为参数传递给旧Grid,这样就可以将所有属性设置为相同。
public Grid CloneGrid(Grid input)
{
Grid temp = new Grid();
temp.Width = input.Widht;
... etc
return temp;
}
编辑:
另一种方法是在Style
中将您的属性定义为App.xaml
,然后将其应用于Grid
:
Grid.Style = App.Current.Resources[StyleKey] as Style;