Reputation: 1069
I've read so many postings here on StackOverflow and lots of blog entries but could not find a working answer to my question: I'm developing a windows 10 universal app. I have a listview using an item template. Now I added another item template and want to set with template to use when the application starts. No need to do it item by item, the template should be added for all items.
<Page.Resources>
<DataTemplate x:Key="DataTemplate1">
(...)
</DataTemplate>
<DataTemplate x:Key="DataTemplate2">
(...)
</DataTemplate>
</Page.Resources>
<ListView
x:Name="itemListView"
AutomationProperties.AutomationId="ItemsListView"
AutomationProperties.Name="Items"
TabIndex="1"
Grid.Column="0"
IsSwipeEnabled="False" HorizontalContentAlignment="Stretch"
SelectionChanged="ItemListView_SelectionChanged" IsSynchronizedWithCurrentItem="False"
ItemsSource="{Binding FeedItems}" ItemTemplate="{StaticResource DataTemplate1}" Margin="0,60,0,10" Grid.RowSpan="2">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
What's the easiest way to do it? I've tried so many options, none of them did work :-( Many thanks!
Upvotes: 2
Views: 4266
Reputation: 319
bit old question but first in google search, so , i add my answer you may access template by name define x:name for resource
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="dtPerMeal" x:Name="dtPerMeal">
<TextCell Text="{Binding Product.Name}" Detail="{Binding TotalWeight}" />
</DataTemplate>
<DataTemplate x:Key="dtPerBatch" x:Name="dtPerBatch">
<TextCell Text="{Binding Product.Name}" Detail="0" />
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
and then access it by name in code behind (switching datatemplate on a radiobutton change )
private void rbMeal_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
lvProducts.ItemTemplate = (rbMeal.IsChecked) ? dtPerMeal : dtPerBatch;
}
Upvotes: 0
Reputation: 128061
You can set the ItemTemplate
in code behind:
public MainPage()
{
this.InitializeComponent();
itemListView.ItemTemplate = (DataTemplate)Resources["DataTemplate2"];
}
Upvotes: 4