System.DivideByZeroException in UWP



所以,我对我的Microsoft Visual Studio进行了一些更新。以前,我的 UWP 翻转视图运行良好。基本上,我的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:UsersalishsourcereposTMD_LatestTMD_LatestViewsMainPage.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>

请帮忙:(

如@Abestrad所述,发生这种情况是因为余数运算符的右侧为零。如下所述:

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;
}

最新更新