我希望在运行时更改ListBox的ItemsPanelTemplate。
我有以下XAML,它允许我更改ItemsPanelTemplate;但是,它有破坏ScrollViewer的副作用。
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ie="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
...
<UserControl.Resources>
<ItemsPanelTemplate x:Key="StackPanelTemplate">
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
<ItemsPanelTemplate x:Key="WrapPanelTemplate">
<telerik:RadWrapPanel/>
</ItemsPanelTemplate>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Button Content="StackPanel">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource StackPanelTemplate}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button Content="WrapPanel">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource WrapPanelTemplate}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
<ListBox x:Name="TargetListBox" Grid.Column="1" ItemsSource="{Binding SomeCollection}"/>
</Grid>当您以这种方式更改ItemsPanelTemplate时。在您更改ScrollViewer之前,它似乎处于任何状态,并且使用滚动条不会影响ListBox上的任何更改。
有人能提供任何关于这个问题的洞察力,或者提供一个解决办法吗?
谢谢。
*编辑*
因此,我缩小了问题范围,因为它与虚拟化有关。如果只将VirtualizingStackPanel更改为常规StackPanel,则ScrollViewer不会中断。不过,这对我来说并不是一个解决方案,因为这个ListBox将保存数百个搜索结果。
发布于 2011-11-17 03:02:39
我认为最简单的解决方法是替换整个ListBox,而不仅仅是面板模板。
发布于 2017-07-04 13:44:51
嗯,我也面临着同样的问题,我想要创建一个有产品的ListBox,让用户可以自由地将布局从WrapPanel更改为列表框,从ListBox更改为WrapPanel。因此,要做到这一点,您应该使用样式。(我建议您使用ListView而不是ListBox,因为ListBox中存在滚动问题。不管怎样,两者都会起作用的)。首先,在app.xaml中添加2种样式
WrapPanelTemplateLV
<Style x:Key="WrapPanelTemplateLV" TargetType="ListView">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>和StackPanelTemplateLV
<Style x:Key="StackPanelLV" TargetType="ListBox">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>现在在你的按钮里做这个
// StackPanelLV is on my App.xaml
MyListView.Style = (Style)Application.Current.Resources["StackPanelLV"];现在你有了主意。在两种样式之间转换一些逻辑。我建议你多问这个问题。Changing the styles at runtime in WPF
https://stackoverflow.com/questions/8161504
复制相似问题