更改模板内的元素

时间:2014-10-12 19:00:35

标签: wpf xaml templates itemscontrol

我想重复使用ListView中的ItemsControl,并且很难将ItemsControle放入模板中。
问题是,我想在使用ItemsControlTemplate时更改DataTemplate。

<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 个答案:

答案 0 :(得分:0)

您可以使用Resource动态设置ItemTemplate。只需提供默认Resource DataTemplate,当您需要更改它时,覆盖该资源(使用相同的密钥并放置在距离控件较近的位置)。

 <ListView Grid.Row="1">
    <ItemsControl ItemsSource="{Binding ColumnData}"
                  ItemTemplate="{StaticResource templateKey}"/>
 </ListView>

然后定义一个x:Key templateKey的资源,如下所示:

 <Window.Resources>
   <DataTemplate x:Key="templateKey">
     <Button Content="{Binding}"/>
   </DataTemplate>
 <Window.Resources>

以下是覆盖模板的示例,其中我们在DataTemplate的资源中放置了另一个ListView

<ListView DataContext="{Binding Input}">
   <ListView.Resources>
     <DataTemplate x:Key="templateKey">
       <CheckBox Content="{Binding}"/>
     </DataTemplate>
   </ListView.Resources>
   <!-- ... -->
</ListView>

如果您想在运行时更新模板,则需要使用DynamicResource代替StaticResource