1
///
<summary>
2
///
This class contains a few useful extenders for the ListBox
3
///
</summary>
4
public
class ListBoxExtenders : DependencyObject
5 {
6
#region Properties
7
8
public
static
readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached(
"
AutoScrollToCurrentItem
",
9
typeof(
bool),
typeof(ListBoxExtenders),
new UIPropertyMetadata(
default(
bool), OnAutoScrollToCurrentItemChanged));
10
11
///
<summary>
12
///
Returns the value of the AutoScrollToCurrentItemProperty
13
///
</summary>
14
///
<param name="obj">
The dependency-object whichs value should be returned
</param>
15
///
<returns>
The value of the given property
</returns>
16
public
static
bool GetAutoScrollToCurrentItem(DependencyObject obj)
17 {
18
return (
bool)obj.GetValue(AutoScrollToCurrentItemProperty);
19 }
20
21
///
<summary>
22
///
Sets the value of the AutoScrollToCurrentItemProperty
23
///
</summary>
24
///
<param name="obj">
The dependency-object whichs value should be set
</param>
25
///
<param name="value">
The value which should be assigned to the AutoScrollToCurrentItemProperty
</param>
26
public
static
void SetAutoScrollToCurrentItem(DependencyObject obj,
bool value)
27 {
28 obj.SetValue(AutoScrollToCurrentItemProperty, value);
29 }
30
31
#endregion
32
33
#region Events
34
35
///
<summary>
36
///
This method will be called when the AutoScrollToCurrentItem
37
///
property was changed
38
///
</summary>
39
///
<param name="sender">
The sender (the ListBox)
</param>
40
///
<param name="e">
Some additional information
</param>
41
public
static
void OnAutoScrollToCurrentItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
42 {
43
var listBox = sender
as ListBox;
44
if ((listBox ==
null) || (listBox.Items ==
null))
45
return;
46
47
var enable = (
bool)e.NewValue;
48
var autoScrollToCurrentItemWorker =
new EventHandler((_1, _2) => OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition));
49
50
if (enable)
51 listBox.Items.CurrentChanged += autoScrollToCurrentItemWorker;
52
else
53 listBox.Items.CurrentChanged -= autoScrollToCurrentItemWorker;
54 }
55
56
///
<summary>
57
///
This method will be called when the ListBox should
58
///
be scrolled to the given index
59
///
</summary>
60
///
<param name="listBox">
The ListBox which should be scrolled
</param>
61
///
<param name="index">
The index of the item to which it should be scrolled
</param>
62
public
static
void OnAutoScrollToCurrentItem(ListBox listBox,
int index)
63 {
64
if (listBox !=
null && listBox.Items !=
null && listBox.Items.Count > index && index >=
0)
65 listBox.ScrollIntoView(listBox.Items[index]);
66 }
67
68
#endregion
69