在导航ListCollectionView时更新SelectedItem

时间:2015-10-30 08:18:00

标签: c# wpf mvvm listbox

我有一个ListCOllectionView绑定到Listbox。当我点击它时,我可以选择一个项目。现在我希望能够转到列表框中的上一个和下一个项目并同时选择它。

我的列表框

<ListBox x:Name="Imported_images" SelectedItem="{Binding SelectedImage}" ItemsSource="{Binding SortedImageLibrary}"/>

<Button x:Name="next" Command="{Binding NextImageCommand}" >
<Button x:Name="previous" Command="{Binding PreviousImageCommand}">

视图模型

private ListCollectionView _sortedImageLibrary;
public ListCollectionView SortedImageLibrary
{
    get
    {
        if (_sortedImageLibrary == null) 
        {
            _sortedImageLibrary = new ListCollectionView(ImageLibrary);
            _sortedImageLibrary.IsLiveSorting = true;
            _sortedImageLibrary.CustomSort = new ImageComparer();                     
         }
        return _sortedImageLibrary; 
    }
    set
    {
        _sortedImageLibrary = value; RaisePropertyChanged();
    }
}

private Image _selectedImage;
public Image SelectedImage   
{
    get { return _selectedImage; }
    set { _selectedImage = value; RaisePropertyChanged("SelectedImage"); }
}

public RelayCommand NextImageCommand { get; set; }
public RelayCommand PreviousImageCommand { get; set; }
public void PreviousImageExecute()
{
    if (SortedImageLibrary.CurrentPosition == 0)
    {
    }
    else
    {
        SortedImageLibrary.MoveCurrentToPrevious();
    }
}
public void NextImageExecute()
{
    if (SortedImageLibrary.CurrentPosition == SortedImageLibrary.Count - 1)
    {
    }
    else
    {
        SortedImageLibrary.MoveCurrentToNext();
    }
}

我可以转到ListCollectionView中的下一个和上一个项目,但SelectedImage不会更新。当我浏览ListCollectionView时,如何更新所选图像?

2 个答案:

答案 0 :(得分:0)

我认为你只需要在导航上设置SelectedImage属性的实例。 PropertyChangedEvent应该在WPF端触发更新。

我不确定,但我猜它看起来应该像这样:

public void PreviousImageExecute()
{
    if (SortedImageLibrary.CurrentPosition == 0)
    {
    }
    else
    {
        SortedImageLibrary.MoveCurrentToPrevious();
    }
    SelectedImage = SortedImageLibrary.CurrentItem as Image;
}
public void NextImageExecute()
{
    if (SortedImageLibrary.CurrentPosition == SortedImageLibrary.Count - 1)
    {
    }
    else
    {
        SortedImageLibrary.MoveCurrentToNext();
    }
    SelectedImage = SortedImageLibrary.CurrentItem as Image;
}

答案 1 :(得分:0)

导航后,应将CurrentItem分配给SelectedImage属性。当然,您需要在分配之前评估导航方法是否返回true。