none
如何在后台切换ListView的ItemsPanelTemplate?通过后台的代码将StackPanel与Warpanel相互切换 RRS feed

  • 问题

  • 想在后台通过事件代码中切换ListView的显示风格ItemsPanelTemplate,当事件触发时,StackPanel与Warpanel相互切换,如何做到?
    2016年12月28日 3:17

答案


  • Hi 轮回的齿轮,

    你可以使用SetValue来重新设置Style的属性值,这样就可以在后台代码中进行动态切换。

    ListView.SetValue(ListView.StyleProperty, this.Resources["Style1"]);
    ListView.SetValue(ListView.StyleProperty, this.Resources["Style2"]);
    

    这些Style是你在窗体资源中为Listview进行定义的,比如下面代码:

    <Style x:Key="Style1" x:Name="a" TargetType="{x:Type ListView}" >
                <Setter Property="ItemsPanel">
                    <Setter.Value>
                        <ItemsPanelTemplate>
                            <StackPanel   Orientation="Vertical">
                            </StackPanel>
                        </ItemsPanelTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="ItemTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <StackPanel Margin="10 20 0 0" >
                                <Label MaxWidth="112"  Margin="0,10,0,0" >
                                    <TextBlock TextWrapping="Wrap" TextAlignment="Center" FontSize="12" 
    
    FontWeight="Bold" Text="{Binding Name}" Height="27" Width="105"></TextBlock>
                                </Label>
                            </StackPanel>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
    
            <Style x:Key="Style2" x:Name="a2" TargetType="{x:Type ListView}" >
               
            </Style>

    Best Regards,

    Yohann Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年12月28日 14:07
    版主