我可以通过编程方式设置WPF ListBox滚动条的位置吗?默认情况下,我希望它在中心。
答案 0 :(得分:7)
要在ListBox中移动垂直滚动条,请执行以下操作:
以下是一份工作样本:
XAML:
<Window x:Class="ListBoxScrollPosition.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Window_Loaded"
Title="Main Window" Height="100" Width="200">
<DockPanel>
<Grid>
<ListBox x:Name="myListBox">
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
</ListBox>
</Grid>
</DockPanel>
</Window>
C#
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Get the border of the listview (first child of a listview)
Decorator border = VisualTreeHelper.GetChild(myListBox, 0) as Decorator;
if (border != null)
{
// Get scrollviewer
ScrollViewer scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null)
{
// center the Scroll Viewer...
double center = scrollViewer.ScrollableHeight / 2.0;
scrollViewer.ScrollToVerticalOffset(center);
}
}
}
答案 1 :(得分:3)
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
或
myListBox.SelectedIndex = midPoint
这取决于您是否想要显示或选择中间项目。
答案 2 :(得分:0)
我刚刚更改了Zamboni的一些代码并添加了位置计算。
var border = VisualTreeHelper.GetChild(list, 0) as Decorator;
if (border == null) return;
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer == null) return;
scrollViewer.ScrollToVerticalOffset((scrollViewer.ScrollableHeight/list.Items.Count)*
(list.Items.IndexOf(list.SelectedItem) + 1));
答案 3 :(得分:0)
我有一个名为MusicList的ListView。播放音乐后,MusicList会自动移至下一个元素。我为Player.Ended事件创建一个事件处理程序,如下所示(la Zamboni):
$scope.printRepayment = function() {
var documentDefinition = generatePDF(); pdfMake.createPdf(documentDefinition).print();
}
var generatePDF = function() {
var repayments = $scope.repayments;
var rows = [
[
{ text: "Payment No", style: "tableHeader" },
{ text: "Installment", style: "tableHeader" },
]
];
for (var i = 0; i < repayments.length; i++) {
rows.push([
{ text: i + 1, style: "tablefirst" },
{
text:
"AED " +
numberWithCommas(
parseFloat(repayments[i].installment).toFixed(2)
),
style: "tableOther"
},
]);
}
return {
content: [
{ text: "Repayment schedule", style: "subheader" },
{
style: "tableExample",
table: {
widths: ["*", "*", "*", "*", "*"],
body: rows
},
layout: {
vLineColor: function(i, node) {
return "#ECF3FE";
}
}
}
],
styles: {
tabletop: {
margin: [10, 0, 0, 10]
},
tabletopHeader: {
fontSize: 16,
bold: true
}
}
};
};
您将在底部看到下一个元素。
答案 4 :(得分:-1)
我不认为ListBox有这个,但ListViews有EnsureVisible方法将滚动条移动到所需的位置,以确保显示一个项目。