WPF以编程方式将ListView的选定项移动到视图中

时间:2018-07-24 00:24:51

标签: c# wpf listview

我在ListView1中使用SelectionChanged事件,该事件将更改字符串:“ dr.CustomBackgroundColor”。该字符串用于查找索引并更改目标ListView中的选择:“ SetColorListView”。哪个按预期工作!

但是“ SetColorListView”中的选择不会“跳转”到视图中。即。它被选中,但是我必须滚动才能找到它...

是否有一种简便的方法可以自动显示SelectedItem?

<ListView x:Name="SetColorListView" Focusable="False"
     ItemsSource="{Binding SystemColorObservableCollection, UpdateSourceTrigger=PropertyChanged}"
     SelectedValuePath="HexValue" 
     SelectedValue="{Binding objGantChartClass.CustomBackgroundColor, Mode=TwoWay}" 
     SelectedIndex="{Binding SystemColorObservableCollectionSelectedIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True">

SystemColorObservableCollectionSelectedIndex = SystemColorObservableCollection.IndexOf(SystemColorObservableCollection.Where(c => c.HexValue == dr.CustomBackgroundColor).FirstOrDefault());

1 个答案:

答案 0 :(得分:1)

您可以使用行为:

using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Jarloo.Sojurn.Behaviors
{
    public sealed class ScrollIntoViewBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SelectionChanged += ScrollIntoView;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.SelectionChanged -= ScrollIntoView;
            base.OnDetaching();
        }

        private void ScrollIntoView(object o, SelectionChangedEventArgs e)
        {
            var b = (ListBox)o;
            if (b == null) return;
            if (b.SelectedItem == null) return;

            var item = (ListBoxItem)((ListBox)o).ItemContainerGenerator.ContainerFromItem(((ListBox)o).SelectedItem);
            if (item != null) item.BringIntoView();
        }
    }
}

然后在列表框内这样声明它:

<ListBox ItemsSource="{Binding Shows.View}" Background="{x:Null}"  Grid.Row="1" Grid.Column="0"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled" Style="{StaticResource NoFocusListBoxStyle}" SelectedItem="{Binding SelectedShow}">

    <i:Interaction.Behaviors>
        <behaviors:ScrollIntoViewBehavior />
    </i:Interaction.Behaviors>

    <ListBox.ItemTemplate>
        <DataTemplate>

...

您还需要将以下声明为命名空间:

xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

我从GitHub上的一个开放源代码项目中获取了此代码,如果您需要在实际中查看它或需要更多上下文,可以在Sojurn处查看完整源代码。

希望这会有所帮助!