因此,我对Microsoft Visual Studio进行了一些更新。以前,我的UWP flipview运行良好。基本上,我的Flipview从本地图片库读取图像。现在,如果我运行我的UWP,则会出现此异常!
System.DivideByZeroException
HResult=0x80020012
Message=Attempted to divide by zero.
Source=TMD_Latest
StackTrace:
at TMD_Latest.Views.MainPage.ChangeImage(Object sender, Object o) in C:\Users\alish\source\repos\TMD_Latest\TMD_Latest\Views\MainPage.xaml.cs:line 97
private void ChangeImage(object sender, object o)
{
//Get the number of items in the flip view
var totalItems = TheFlipView.Items.Count;
//Figure out the new item's index (the current index plus one, if the next item would be out of range, go back to zero)
//This line below is the exception!
var newItemIndex = (TheFlipView.SelectedIndex + 1) % totalItems;
//Set the displayed item's index on the flip view
TheFlipView.SelectedIndex = newItemIndex;
}
我的xaml:
<Grid VariableSizedWrapGrid.ColumnSpan="5"
VariableSizedWrapGrid.RowSpan="5"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Padding="0 30 20 20"
Margin="200,-100,0,10"
Background="Transparent">
<x21:Grid.RowDefinitions>
<x21:RowDefinition Height="405*"/>
<x21:RowDefinition Height="21*"/>
<x21:RowDefinition Height="425*"/>
</x21:Grid.RowDefinitions>
<FlipView x:Name="TheFlipView"
SelectionChanged="DisplayedItemChanged" Margin="-235,205.6,30,-1221.6" x21:Grid.Row="2" >
<FlipView.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,10" >
<Image HorizontalAlignment="Center" VerticalAlignment="Stretch" Source="{Binding}"
Stretch="Fill" Margin="0,-200,0,0" />
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Grid>
请帮助:(
答案 0 :(得分:2)
如@Abestrad所述,这是因为余数运算符的右侧为零。如here所述:
x % y
的结果是x - (x / y) * y
产生的值。 如果y为零,则抛出System.DivideByZeroException
。
一种解决此情况的方法是将余数运算符包装在if
条件下:
if (totalItems > 0)
{
var newItemIndex = (TheFlipView.SelectedIndex + 1) % totalItems;
//Set the displayed item's index on the flip view
TheFlipView.SelectedIndex = newItemIndex;
}