假设我有一个包含许多项目的列表框,以便出现垂直滚动,但我隐藏了滚动条
ScrollViewer.VerticalScrollBarVisibility="Hidden"
有什么方法可以添加一个可以向下滚动的按钮吗? iv 尝试添加
Command="ScrollBar.LineDownCommand"
到一个按钮,但没有任何效果。
最佳答案
您需要告诉 WPF 从哪里开始查找命令处理程序。在不告诉它的情况下,它会开始从 Button
查找,但找不到任何处理 LineDownCommand
的内容。不幸的是,将其设置为 ListBox
是不够的,因为 ScrollViewer
作为其模板的一部分位于 ListBox
内部 ,所以 WPF 仍然找不到它。
将其设置为 ListBoxItem
之一是无稽之谈,但有效:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox x:Name="_listBox" ScrollViewer.VerticalScrollBarVisibility="Hidden">
<ListBoxItem x:Name="_listBoxItem">One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
<ListBoxItem>One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
<ListBoxItem>One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
<ListBoxItem>One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
</ListBox>
<Button Grid.Row="1" Command="ScrollBar.LineDownCommand" CommandTarget="{Binding ElementName=_listBoxItem}">Scroll Down</Button>
</Grid>
</Window>
更好的方法是重新模板化 ListBox
并将 Button
粘贴到模板内,或者连接 CommandTarget
在代码隐藏中。
关于WPF 列表框向下滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/650085/