первая попытка не удалась - см. Ниже
Вам необходимо реализовать IValueConverter
и установить для него атрибут Converter
привязки.
Создайте класс, который наследуется от IValueConverter
, и в методе Convert
вы приведете параметр value
к ListBox
(поскольку вы будете привязывать TextBox
к ListBox
сам и позволяя преобразователю превратить это во что-то значимое).
Затем получите ссылку на свойство ListBox
SelectedIndex
.
Вы хотите вернуть listBox.Items[selectedIndex + 1]
из метода.
Вы можете оставить метод ConvertBack
невыполненным.
Вам также придется обработать случай, когда выбран последний элемент в ListBox
, потому что индекс + 1 будет выходить за пределы. Может быть, вы хотите вернуть первый товар; может быть, вы хотите вернуть null
или string.Empty
.
обновление: пользовательский ListBox
В соответствии с запросом приведен пример, в котором используется пользовательский ListBox с дополнительным свойством [Dependency], которое называется ItemAfterSelected.
Сначала код для производного элемента управления:
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);
}
}
}
Вот пример окна, которое показывает, как использовать и привязать к элементу управления (вы можете перетащить его в приложение и запустить, чтобы увидеть его в действии).
<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>