问题
I want to reuse the the ItemsControl from my ListView and its not really hard to put the ItemsControle into an Template.
The problem is, I want to change the DataTemplate when I use my ItemsControlTemplate.
<ListView DataContext="{Binding Input}">
<ItemsControl ItemsSource="{Binding Columns}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Label Content="{Binding ColumnHeader}"></Label>
</StackPanel>
<ListView Grid.Row="1">
<ItemsControl ItemsSource="{Binding ColumnData}">
<ItemsControl.ItemTemplate>
<!--This should be changed when I reuse my ItemsControl-->
<DataTemplate>
<Button Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ListView>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ListView>
回答1:
You can use a Resource
to set that ItemTemplate
dynamically. Just provide a default Resource
of DataTemplate
, when you need to change it, override that resource (using the same key and place in a closer place to the control).
<ListView Grid.Row="1">
<ItemsControl ItemsSource="{Binding ColumnData}"
ItemTemplate="{StaticResource templateKey}"/>
</ListView>
Then define a resource with x:Key
of templateKey
like this:
<Window.Resources>
<DataTemplate x:Key="templateKey">
<Button Content="{Binding}"/>
</DataTemplate>
<Window.Resources>
Here is an example of overriding the template, in which we place another DataTemplate
inside the ListView
's Resources:
<ListView DataContext="{Binding Input}">
<ListView.Resources>
<DataTemplate x:Key="templateKey">
<CheckBox Content="{Binding}"/>
</DataTemplate>
</ListView.Resources>
<!-- ... -->
</ListView>
If you want to update the template at runtime, you need to use DynamicResource
instead of StaticResource
.
来源:https://stackoverflow.com/questions/26328807/change-element-inside-template