简体   繁体   中英

Change Xaml-Image.Source from a new Class (Xamarin)

im new to Xamarin and i try to change the Image.Source from a Xaml.Page via a new class. Maybe someone can help me out with this.

eg I have a PageX.xaml with a Image x:Name="ImageX" and a new ClassY

Now i would like to change the ImageX.Source from PageX when circumstance Z occurs.

Some insights on my code:

Xaml:

<Image
   x:Name="ImageNonBossAnimation"
   BackgroundColor="Transparent"
   Grid.Row="18"
   Grid.RowSpan="10"
   Grid.Column="20"
   Grid.ColumnSpan="7"
/>

new Class:

public static async void AttackSkills(string pressedSkill, string monsterType)
{
   if (pressedSkill == "SkillX")
      {
         if (monsterType == "nonBoss")
            {
               for (int animCounter = 1; animCounter <= 6; animCounter++)
                   {
                       PageX.ImageNonBossAnimation.Source = "anim_stroke" + animCounter.ToString();
                       await Task.Delay(30);
                   }
                   Page.ImageNonBossAnimation.Source = null;
            }
            --another occasion takes place here--
      }
}

I really would appreciate any help.

ImageNonBossAnimation is not a static Item in PageX, So you can't access it like PageX.ImageNonBossAnimation pass Image as reference to AttackSkills this method and then change image source. Like

public static async void AttackSkills(string pressedSkill, string monsterType, ref Image ximgae)
{
   if (pressedSkill == "SkillX")
      {
         if (monsterType == "nonBoss")
            {
               for (int animCounter = 1; animCounter <= 6; animCounter++)
                   {
                       ximage.Source = "anim_stroke" + animCounter.ToString();
                       await Task.Delay(30);
                   }
                   ximage.Source = null;
            }
            --another occasion takes place here--
      }
}

and call method like AttackSkills(parem1,parem2,ref ImageNonBossAnimation);

With the help of @CodeSeekers i found a Solution.

It´s relatively easy, you can call your new class Y from the.cs bound to your.xaml with:

Code in.cs

ClassY.AttackSkills(passedSkill, monsterType, ImageX);

class Y Code

public static async void AttackSkills(string pressedSkill, string monsterType, Image ImageNonBossAnimation)
    {
        if (pressedSkill == "SkillX")
        {
            if (monsterType == "nonBoss")
            {
                for (int animCounter = 1; animCounter <= 6; animCounter++)
                {
                    ImageX.Source = "anim_stroke" + animCounter.ToString();
                    await Task.Delay(30);
                }
                ImageX = null;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM