如何在 windows 通用应用程序中动态创建 hubsections
How to dynamically create hubsections in windows universal apps
我有一个 ObservableCollection
,其中包含许多对象,这些对象取决于用户与应用程序的交互。
我想将每个对象表示为一个 HubSection
,由于我不知道对象的数量,因此 HubSections 必须从 View 的代码后面动态生成。
在视图后面的代码(xaml.cs 文件)中,我创建了一个遍历集合的循环,并在每次迭代中开始创建一个 HubSection。
for (int i = 0; i < list_size; i++)
{
tempHubSection = new HubSection();
tempHubSection.Header = vm.MyCollection[i].Name;
DataTemplate dt = new DataTemplate();
???
mainHub.Sections.Add(tempHubSection);
}
但我对如何创建 DataTemplate 并在其中插入 Grid 感到有点困惑,例如:
<HubSection Width="700" Header="object-1">
<DataTemplate>
<Grid>
...
</Grid>
</DataTemplate>
</HubSection>
谢谢。
将您的 DataTemplate
代码移动到 app.xaml
文件的资源部分,给出名称,例如 myTemplate
.
<DataTemplate x:Key="myTemplate">
<Grid>
...
</Grid>
</DataTemplate>
然后您就可以在代码中分配它了:
mainHub.Template = (ControlTemplate)App.Current.Resources["myTemplate"];
我有一个 ObservableCollection
,其中包含许多对象,这些对象取决于用户与应用程序的交互。
我想将每个对象表示为一个 HubSection
,由于我不知道对象的数量,因此 HubSections 必须从 View 的代码后面动态生成。
在视图后面的代码(xaml.cs 文件)中,我创建了一个遍历集合的循环,并在每次迭代中开始创建一个 HubSection。
for (int i = 0; i < list_size; i++)
{
tempHubSection = new HubSection();
tempHubSection.Header = vm.MyCollection[i].Name;
DataTemplate dt = new DataTemplate();
???
mainHub.Sections.Add(tempHubSection);
}
但我对如何创建 DataTemplate 并在其中插入 Grid 感到有点困惑,例如:
<HubSection Width="700" Header="object-1">
<DataTemplate>
<Grid>
...
</Grid>
</DataTemplate>
</HubSection>
谢谢。
将您的 DataTemplate
代码移动到 app.xaml
文件的资源部分,给出名称,例如 myTemplate
.
<DataTemplate x:Key="myTemplate">
<Grid>
...
</Grid>
</DataTemplate>
然后您就可以在代码中分配它了:
mainHub.Template = (ControlTemplate)App.Current.Resources["myTemplate"];