gpt4 book ai didi

c# - 列表框滚动条不跟随所选项目(使用 ICollectionView)

转载 作者:行者123 更新时间:2023-12-03 21:50:09 25 4
gpt4 key购买 nike

我正在尝试在 WPF 中实现 MVVM 模式。我关注了 Jeremy Alles 的 Very simple MVVM demo application 。我有一个 ListBox,它绑定(bind)到 ObservableCollection:

<ListBox
Name="myListBox"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Persons}">
<ListBox.ItemTemplate>
<DataTemplate>
<views:PersonsView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

我添加了一个ICollectionView来管理ListBox上的所选项目。它还允许我有两个按钮,允许我选择列表中的上一个和下一个项目。

private void GoToPrevious()
{
this.collectionView.MoveCurrentToPrevious();
}
private void GoToNext()
{
this.collectionView.MoveCurrentToNext();
}

一切都很好,但是,当所选项目位于列表框显示区域下方时,列表框的滚动条不会相应移动。

如何使列表框的滚动条/显示区域与所选项目同步?

最佳答案

我找到了答案。我需要使用

myListBoxItem.BringIntoView();

问题是我不想添加任何代码隐藏,因为我正在实现 MVVM。

解决方案是使用附加行为。乔什·史密斯(Josh Smith)有一篇关于此的精彩文章:Introduction to Attached Behaviors in WPF .

我为 ListBox 中的项目的样式添加了 Setter:

<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter
Property="custom:ListBoxItemBehavior.IsBroughtIntoViewWhenSelected"
Value="True" />
</Style>
</ListBox.ItemContainerStyle>

并添加了以下类(仅将 Josh 的文章中的 TreeView 更改为 ListBox):

public static class ListBoxItemBehavior
{
#region IsBroughtIntoViewWhenSelected

public static bool GetIsBroughtIntoViewWhenSelected(ListBoxItem listBoxItem)
{
return (bool)listBoxItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);
}

public static void SetIsBroughtIntoViewWhenSelected(
ListBoxItem listBoxItem, bool value)
{
listBoxItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
}

public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
DependencyProperty.RegisterAttached(
"IsBroughtIntoViewWhenSelected",
typeof(bool),
typeof(ListBoxItemBehavior),
new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));

static void OnIsBroughtIntoViewWhenSelectedChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
ListBoxItem item = depObj as ListBoxItem;
if (item == null)
return;

if (e.NewValue is bool == false)
return;

if ((bool)e.NewValue)
item.Selected += OnListBoxItemSelected;
else
item.Selected -= OnListBoxItemSelected;
}

static void OnListBoxItemSelected(object sender, RoutedEventArgs e)
{
// Only react to the Selected event raised by the ListBoxItem
// whose IsSelected property was modified. Ignore all ancestors
// who are merely reporting that a descendant's Selected fired.
if (!Object.ReferenceEquals(sender, e.OriginalSource))
return;

ListBoxItem item = e.OriginalSource as ListBoxItem;
if (item != null)
item.BringIntoView();
}

#endregion // IsBroughtIntoViewWhenSelected
}

它有效!!

关于c# - 列表框滚动条不跟随所选项目(使用 ICollectionView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com