first attempt failed -- see below
You need to implement an IValueConverter
and set it to the Converter
attribute of the binding.
Create a class that inherits from IValueConverter
, and in the Convert
method, you'll cast the value
parameter to ListBox
(because you'll be binding the TextBox
to the ListBox
itself and letting the converter turn that into something meaningful).
Then get a reference to the ListBox
's SelectedIndex
property.
You want to return listBox.Items[selectedIndex + 1]
from the method.
You can leave the ConvertBack
method unimplemented.
You'll also have to handle the case where the last item in the ListBox
is selected, because index + 1 will be out of bounds. Maybe you want to return the first item; maybe you want to return null
or string.Empty
.
update: custom ListBox
As requested, here is a sample that uses a custom ListBox with an additional [Dependency] property called "ItemAfterSelected."
First, the code for the derived control:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public class PlusOneListBox : ListBox
{
public PlusOneListBox()
{
SelectionMode = SelectionMode.Single;
}
public object ItemAfterSelected
{
get { return GetValue(ItemAfterSelectedProperty); }
set { SetValue(ItemAfterSelectedProperty, value); }
}
public static readonly DependencyProperty ItemAfterSelectedProperty = DependencyProperty.Register(
"ItemAfterSelected", typeof (object), typeof (PlusOneListBox));
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
var newly_selected = e.AddedItems;
if (newly_selected == null) ItemAfterSelected = null;
else
{
var last_index = Items.Count - 1;
var index = Items.IndexOf(newly_selected[0]);
ItemAfterSelected = index < last_index
? Items[index + 1]
: null;
}
base.OnSelectionChanged(e);
}
}
}
Here is a sample window that shows how to use and bind to the control (you can drop this in to an app and run it to see it in action).
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:WpfApplication1" xmlns:System="clr-namespace:System;assembly=mscorlib" Padding="24">
<StackPanel>
<custom:PlusOneListBox x:Name="custom_listbox">
<custom:PlusOneListBox.Items>
<System:String>one</System:String>
<System:String>two</System:String>
<System:String>three</System:String>
<System:String>four</System:String>
<System:String>five</System:String>
<System:String>six</System:String>
</custom:PlusOneListBox.Items>
</custom:PlusOneListBox>
<StackPanel Orientation="Horizontal" Margin="8">
<TextBlock Text="Selected: " />
<TextBlock Text="{Binding SelectedItem, ElementName=custom_listbox}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="8">
<TextBlock Text="Next: " />
<TextBlock Text="{Binding ItemAfterSelected, ElementName=custom_listbox}" />
</StackPanel>
</StackPanel>
</Window>