본문 바로가기

.NET/WPF

[WPF]ListView의 Scrollbar가 자동으로 현재 진행 중인 row에 맞게 아래로 동작

 You have to add a reference to System.Windows.Interactivity to use Behavior<T> class

Behavior

public class ScrollIntoViewForListView : Behavior<ListView>
{
   
/// <summary>
   
///  When Beahvior is attached
   
/// </summary>
   
protected override void OnAttached()
   
{
       
base.OnAttached();
       
this.AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
   
}

   
/// <summary>
   
/// On Selection Changed
   
/// </summary>
   
/// <param name="sender"></param>
   
/// <param name="e"></param>
   
void AssociatedObject_SelectionChanged(object sender,
                                          
SelectionChangedEventArgs e)
   
{
       
if (sender is ListView)
       
{
           
ListView listView = (sender as ListView);
           
if (listView .SelectedItem != null)
           
{
                listView
.Dispatcher.BeginInvoke(
                   
(Action) (() =>
                                 
{
                                      listView
.UpdateLayout();
                                     
if (listView .SelectedItem !=
                                         
null)
                                          listView
.ScrollIntoView(
                                              listView
.SelectedItem);
                                 
}));
           
}
       
}
   
}
   
/// <summary>
   
/// When behavior is detached
   
/// </summary>
   
protected override void OnDetaching()
   
{
       
base.OnDetaching();
       
this.AssociatedObject.SelectionChanged -=
           
AssociatedObject_SelectionChanged;

   
}
}

Usage

Add alias to XAML as xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

then in your Control

      <ListView ItemsSource="{Binding Path=MyList}"
                 
SelectedItem="{Binding Path=MyItem,
                                         Mode=TwoWay}"

                 
SelectionMode="Single">
           
<i:Interaction.Behaviors>
               
<Behaviors:ScrollIntoViewForListView />
           
</i:Interaction.Behaviors>
       
</ListView>

Now When ever "MyItem" property is set in ViewModel the List will be scrolled when changes are refelected.

 


 

From: http://stackoverflow.com/questions/8827489/scroll-wpf-listbox-to-the-selecteditem-set-in-code-in-a-view-model/8828389#8828389

'.NET > WPF' 카테고리의 다른 글

WPF MSDN 참고 목록  (0) 2014.07.18
WPF에서 Window Message 다루기  (0) 2013.07.18
[WPF]데이터를 정렬하는 ListView 샘플  (0) 2013.07.10
데이터 바인딩 개념  (0) 2013.06.17
2,000 Things You Should Know About WPF  (0) 2012.12.27