我尝试使用两个按钮实现简单的下一个上一个图像预览,但下面的代码仅适用于3个图像。如何让它对任意数量的图像更具动态性?我将不胜感激任何帮助。
private void left_arrow_btn_Click(object sender, RoutedEventArgs e)
{
if (x == custom_studio_images.Count - 2)
{
x = custom_studio_images.Count;
//System.Windows.MessageBox.Show(x.ToString());
CustomStudio.Children.RemoveAt(LargePic.Children.Count);
CustomStudio.Children.Add(custom_studio_images.ElementAt(x - 1));
}
else
{
CustomStudio.Children.RemoveAt(LargePic.Children.Count);
CustomStudio.Children.Add(custom_studio_images.ElementAt(x - 2));
//System.Windows.MessageBox.Show(x.ToString());
x--;
}
}
private void right_arrow_btn_Click(object sender, RoutedEventArgs e)
{
if (CustomStudio.Children.Count > 0)
{
CustomStudio.Children.RemoveAt(LargePic.Children.Count); //clear first item in StackPanel
}
if (x == custom_studio_images.Count )
{
x = 0;
CustomStudio.Children.Add(custom_studio_images.ElementAt(x));
x++;
}
else
{
CustomStudio.Children.Add(custom_studio_images.ElementAt(x)); //show picture for next available studio in a set
x++;
}
}
答案 0 :(得分:2)
您应该使用视图模型实现MVVM解决方案,该模型公开图像列表,当前图像以及导航到上一个和下一个图像的两个命令:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
PreviousImageCommand = new RelayCommand(PreviousImage);
NextImageCommand = new RelayCommand(NextImage);
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand PreviousImageCommand { get; set; }
public ICommand NextImageCommand { get; set; }
public List<ImageSource> Images { get; set; }
public ImageSource CurrentImage
{
get
{
if (currentImageIndex < Images.Count)
{
return Images[currentImageIndex];
}
return null;
}
}
private int currentImageIndex;
private void PreviousImage(object o)
{
if (Images.Count > 0)
{
// add Image.Count to avoid negative index
currentImageIndex = (currentImageIndex + Images.Count - 1) % Images.Count;
OnPropertyChanged("CurrentImage");
}
}
private void NextImage(object o)
{
if (Images.Count > 0)
{
currentImageIndex = (currentImageIndex + 1) % Images.Count;
OnPropertyChanged("CurrentImage");
}
}
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
现在,您将在XAML中绑定此视图模型的属性,如下所示:
<Image Source="{Binding CurrentImage}"/>
...
<Button Content="Prev" Command="{Binding PreviousImageCommand}"/>
<Button Content="Next" Command="{Binding NextImageCommand}"/>
答案 1 :(得分:0)
通常使用可用图像的数量。
如果你经过最后一个,请用模运算符索引开头:
CustomStudio.Children.Add(custom_studio_images.ElementAt(x % custom_studio_images.Count));
有问题的部分是你的if语句:
if (x == custom_studio_images.Count - 2)
{
x = custom_studio_images.Count; ...
点击count - 2
后,您将其重新设置为计数。你永远不会低于这一点。