正如其他人所提到的,当我们没有上下文时,很难准确地提供帮助。将您的问题提炼成最小的代码表示会非常有帮助。例如,如果您的控件绑定到类上的单个属性,Rushi Soni 的答案将起作用,但如果您将 TextBlocks 直接绑定到 ObservableCollection,则还有另一个答案:
默认情况下,绑定到集合的非列表控件(如TextBlock)将显示列表中的“当前”项。 WPF 维护一个跟踪当前项目的集合的(有点神奇的)视图。您可以通过调用CollectionViewSource.GetDefaultView(ObservableCollection) 访问集合视图,并在返回的ICollectionView 接口上使用方法MoveCurrentToPrevious、MoveCurrentToNext、IsCurrentBeforeFirst 和IsCurrentAfterLast 操作当前项。
此场景的完整代码:
XAML:
<UserControl.Resources>
<!-- the MyCollection type is derived from ObservableCollection<MyItem> -->
<my:MyCollection x:Key="myCollection">
<my:MyItem Text="One" Anzhal="1"/>
<my:MyItem Text="Two" Anzhal="2"/>
<my:MyItem Text="Three" Anzhal="3"/>
</my:MyCollection>
</UserControl.Resources>
<!-- data context of the top level control is the observable collection defined here in XAML, but
could also be created and assigned in code -->
<DockPanel Name="grid1" DataContext="{StaticResource myCollection}" >
<!-- navigation controls -->
<Grid DockPanel.Dock="Top" >
<Button HorizontalAlignment="Left" Content="< Previous" Name="buttonPrev" Click="buttonPrev_Click" />
<Button HorizontalAlignment="Right" Content="Next >" Name="buttonNext" Click="buttonNext_Click" />
</Grid>
<!-- display of the current item -->
<TextBlock Padding="5" DockPanel.Dock="Top" Text="{Binding Text}" />
<TextBlock Padding="5" DockPanel.Dock="Top" Text="{Binding Anzhal}" />
<!-- list display of all items (not necessary but helpful for visualizing the behavior) -->
<ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Text" />
</DockPanel>
集合和包含项的类定义:
public class MyCollection : ObservableCollection<MyItem> { }
public class MyItem
{
// NOTE: these must be get/set properties in order for binding to work
public string Text { get; set; }
public int Anzhal { get; set; }
}
以及处理 Next/Previous 按钮点击的代码,它演示了到达集合末端时的环绕:
ICollectionView GetView()
{
// use FindResource() to retrieve the collection since it is defined in XAML
// Then we retrieve WPF's view into the collection so we can manipulate the
// current item (next, previous)
return CollectionViewSource.GetDefaultView(FindResource("myCollection"));
}
private void buttonNext_Click(object sender, RoutedEventArgs e)
{
var view = GetView();
// wrap around behavior
view.MoveCurrentToNext();
if (view.IsCurrentAfterLast) {
view.MoveCurrentToFirst();
}
}
private void buttonPrev_Click(object sender, RoutedEventArgs e)
{
var view = GetView();
// wrap around behavior
view.MoveCurrentToPrevious();
if (view.IsCurrentBeforeFirst) {
view.MoveCurrentToLast();
}
}
希望对您有所帮助。