C# Xamarin.Android Calling Dialogfragment from recyclerView - c#

I would like to display diaglog fragment by clicking a button/imageView (By clicking the sAddButton)from recyclerView. But when I clicked the button nothing shows up.
How do I achieve that here is my code.
My RecyclerView Adapter
I added an pulic eventhandler in myadapter (StockInItemClick)
then created a delegate method to invoke the eventhandler(OnStockInClick)
then pass the delegate method as parameter on my adapterview holder
then Implement the delegate method on my adapterview holder.
internal class StocksAdapter : RecyclerView.Adapter
{
public event EventHandler<StocksAdapterClickEventArgs> ItemClick;
public event EventHandler<StocksAdapterClickEventArgs> ItemLongClick;
public event EventHandler<StocksAdapterClickEventArgs> StockInItemClick;
List<Products> items;
public StocksAdapter(List<Products> data)
{
items = data;
}
// Create new views (invoked by the layout manager)
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
//Setup your layout here
View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.stock_rView, parent, false);
//var id = Resource.Layout.__YOUR_ITEM_HERE;
//itemView = LayoutInflater.From(parent.Context).
// Inflate(id, parent, false);
var vh = new StocksAdapterViewHolder(itemView, OnClick, OnLongClick, OnStockInClick);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var holder = viewHolder as StocksAdapterViewHolder;
//holder.TextView.Text = items[position];
holder.sNameText.Text = items[position].PName;
holder.sQtyText.Text = items[position].QtyonHand;
}
public override int ItemCount => items.Count;
void OnClick(StocksAdapterClickEventArgs args) => ItemClick?.Invoke(this, args);
void OnLongClick(StocksAdapterClickEventArgs args) => ItemLongClick?.Invoke(this, args);
void OnStockInClick(StocksAdapterClickEventArgs args) => StockInItemClick?.Invoke(this, args);
}
public class StocksAdapterViewHolder : RecyclerView.ViewHolder
{
//public TextView TextView { get; set; }
public TextView sNameText { get; set; }
public TextView sQtyText { get; set; }
public ImageButton sAddButton { get; set; }
public StocksAdapterViewHolder(View itemView, Action<StocksAdapterClickEventArgs> clickListener,
Action<StocksAdapterClickEventArgs> longClickListener,
Action<StocksAdapterClickEventArgs> stockInClickListener) : base(itemView)
{
//TextView = v;
sNameText = (TextView)itemView.FindViewById(Resource.Id.sNameTView);
sQtyText = (TextView)itemView.FindViewById(Resource.Id.qtyonhandTView);
sAddButton = (ImageButton)itemView.FindViewById(Resource.Id.addButton);
itemView.Click += (sender, e) => clickListener(new StocksAdapterClickEventArgs { View = itemView, Position = AdapterPosition });
itemView.LongClick += (sender, e) => longClickListener(new StocksAdapterClickEventArgs { View = itemView, Position = AdapterPosition });
sAddButton.Click += (sender, e) => longClickListener(new StocksAdapterClickEventArgs { View = itemView, Position = AdapterPosition });
}
}
public class StocksAdapterClickEventArgs : EventArgs
{
public View View { get; set; }
public int Position { get; set; }
}
my code in activity
I implement the eventhandler
then on the event onlcick event(Adapter_StockInItemClick) I called the
dialog fragment.
private void SetupRecyclerView()
{
stockRView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(stockRView.Context));
adapter = new StocksAdapter(StockList);
adapter.StockInItemClick += Adapter_StockInItemClick;
stockRView.SetAdapter(adapter);
}
private void Adapter_StockInItemClick(object sender, StocksAdapterClickEventArgs e)
{
Products thisproducts = StockList[e.Position];
addNewStockInProductsFragment = new AddNewStockInProductsFragment(thisproducts);
var trans = SupportFragmentManager.BeginTransaction();
addNewStockInProductsFragment.Show(trans, "StockIn");
}

Found the problem
sAddButton.Click += (sender, e) => longClickListener(new StocksAdapterClickEventArgs { View = itemView, Position = AdapterPosition });
shouldbe (deleteClickListener) not (longClickListener)
sAddButton.Click += (sender, e) => deleteClickListener(new StocksAdapterClickEventArgs { View = itemView, Position = AdapterPosition });

Related

Connected Animation in UWP

Class Icons.cs:
public class Icon
{
public int IconID { get; set; }
public string Title { get; set; }
public string Room { get; set; }
public string ImageCover { get; set; }
}
public class IconManager
{
public static List<Icon> GetIcons()
{
var Icons = new List<Icon>();
Icons.Add(new Icon { IconID = 1, Title = "Mr.Ha", Room = "611-Room", ImageCover = "Assets/Ha.jpg" });
Icons.Add(new Icon { IconID = 2, Title = "Mr.Synh", Room = "611-Room", ImageCover = "Assets/Synh.jpg" });
return Icons;
}
}
Class MainPage:
public MainPage()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
this.InitializeComponent();
Icons = IconManager.GetIcons();
}
private void ForegroundElement_ItemClick(object sender, ItemClickEventArgs e)
{
var icon = (Icon)e.ClickedItem;
var tittle = icon.Title;
ForegroundElement.PrepareConnectedAnimation("ca1", icon, "ConnectedElement");
switch (tittle)
{
case "Mr.Ha":
Frame.Navigate(typeof(BlankPage1));
break;
}
}
private async void ForegroundElement_Loaded(object sender, RoutedEventArgs e)
{
if(Icons != null)
{
ForegroundElement.ScrollIntoView(Icons, ScrollIntoViewAlignment.Default);
ForegroundElement.UpdateLayout();
ConnectedAnimation animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ca2");
if (animation != null)
{
await ForegroundElement.TryStartConnectedAnimationAsync(
animation, Icons, "ConnectedElement");
}
}
Class BlankPage1:
public BlankPage1()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ConnectedAnimation imageAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ca1");
if (imageAnimation != null)
{
imageAnimation.TryStart(TargetElement);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ca2", TargetElement);
Frame.Navigate(typeof(MainPage));
}
There something wrong with my Animation when I "Navigate Back" to the MainPage. The picture just stay still there then it's disappear, while the listview is done loaded !!My navigation from MainPage to BlankPage1 is fine though!!
Your second connected animation is called ca2, but you are using ca1 in the MainPage's ForegroundElement_Loaded event handler. Because of this, the animation cannot be connected, which results in the behavior you are seeing.

Showing a few popupmenu on one click button in RecyclerView Xamarin Android

I have problem with showing popupmenu. When I clicked on ImageButton , on display shown a few popupmenu(for different elements - in click listener of ClickedPopUpMenu I show toast with position).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Android.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using DexpensMobile.Core.Models;
using DexpensMobile.Core.Services;
using DexpensMobile.Core.Services.AuthService;
using DexpensMobile.Droid.Screens;
using UniversalImageLoader.Core;
using UniversalImageLoader.Core.Display;
using PopupMenu = Android.Widget.PopupMenu;
namespace DexpensMobile.Droid.Adapters
{
public class PostListAdapter : RecyclerView.Adapter
{
protected Activity context = null;
protected IList<PostModel> tasks = new List<PostModel>();
ImageLoader _imageLoader;
private int popPosition;
private int TYPE_HEADER = 0;
private int TYPE_ITEM = 1;
public event EventHandler<int> ItemClick;
public PostListAdapter(IList<PostModel> tasks, Activity context)
{
this.tasks = tasks;
_imageLoader = ImageLoader.Instance;
this.context = context;
}
public PostListAdapter() { }
public override long GetItemId(int position)
{
return position;
}
public override int GetItemViewType(int position)
{
if (IsPositionHeader(position))
return Resource.Layout.wall_header;
return Resource.Layout.ItemPost;
}
private bool IsPositionHeader(int position)
{
return position == 0;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (holder.GetType() == typeof(PostViewHodler))
{
PostViewHodler vh = holder as PostViewHodler;
var item = tasks[position-1];
var _userData = ServiceLocator.GetService<IAuthService>().GetUserData();
vh.ShowPopUpMenuButton.Click += (sender, e) => button_Click(sender, e, position);
var tempText = item.Text;
if (tempText.EndsWith("<br/>"))
tempText = tempText.Substring(0, tempText.Length - 5);
tempText = tempText.Replace("<br/>", "\n");
tempText = Regex.Replace(tempText, #"^\s+$[\n]*", "", RegexOptions.Multiline);
vh.PostText.Text = tempText;
vh.OwnerFullName.Text = item.CreatorName;
vh.DateText.Text = item.CreatedDate.ToString(CultureInfo.InvariantCulture);
vh.LikeText.Text = item.Like.LikesCount > 0
? item.Like.LikesCount.ToString()
: "";
vh.CommentText.Text = item.Comments.Any() ? item.Comments.Count().ToString() : "";
vh.RepostText.Text = item.SharedCount > 0 ? item.SharedCount.ToString() : "";
var options =
new DisplayImageOptions.Builder()
.CacheInMemory(false)
.CacheOnDisk(false)
.Displayer(new RoundedBitmapDisplayer(500))
.Build();
_imageLoader.DisplayImage(item.AvatarUrl, vh.AvatarProfile, options);
}
else if (holder.GetType() == typeof(PostViewHodlerHeader))
{
PostViewHodlerHeader vh = holder as PostViewHodlerHeader;
vh.OwnerNameHeader.Text = "Hi from header :-)";
}
}
private void button_Click(object sender, EventArgs eventArgs, int position)
{
ImageButton im = sender as ImageButton;
PopupMenu menu = new PopupMenu(im.Context, im);
menu.Inflate(Resource.Menu.popup_menu);
//if (item.ApplicationUserId != _userData.UserId)
//{
menu.Menu.FindItem(Resource.Id.editPopUp).SetVisible(false);
menu.Menu.FindItem(Resource.Id.deletePopUp).SetVisible(false);
//}
menu.Show();
Toast.MakeText(context, position.ToString(), ToastLength.Long).Show();
menu.MenuItemClick += (o, args) => PopUpMenuClickListener(o, args, position);
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = null;
if (viewType == Resource.Layout.wall_header)
{
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.wall_header, parent, false);
PostViewHodlerHeader vhHeader = new PostViewHodlerHeader(itemView);
return vhHeader;
}
else if(viewType == Resource.Layout.ItemPost)
{
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ItemPost, parent, false);
PostViewHodler vhBody = new PostViewHodler(itemView, OnClick, tasks);
return vhBody;
}
return null;
}
private void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
public override int ItemCount
{
get { return tasks.Count +1; }
}
private void PopUpMenuClickListener(object sender, PopupMenu.MenuItemClickEventArgs e, int position)
{
switch(e.Item.ItemId)
{
case Resource.Id.copyLinkPopUp:
break;
case Resource.Id.editPopUp:
((WallActivity)context).EditPost(popPosition);
break;
case Resource.Id.deletePopUp:
((WallActivity)context).DeleteItem(popPosition);
break;
}
}
}
public class PostViewHodler : RecyclerView.ViewHolder
{
public TextView OwnerFullName { get; private set; }
public ImageView AvatarProfile { get; private set; }
public TextView DateText { get; private set; }
public TextView PostText { get; private set; }
public TextView LikeText { get; private set; }
public TextView CommentText { get; private set; }
public TextView RepostText { get; private set; }
public ImageButton ShowPopUpMenuButton { get; private set; }
public PostViewHodler(View itemView, Action<int> listener, IList<PostModel> posts) : base(itemView)
{
OwnerFullName = itemView.FindViewById<TextView>(Resource.Id.UserName);
AvatarProfile = itemView.FindViewById<ImageView>(Resource.Id.postAva);
DateText = itemView.FindViewById<TextView>(Resource.Id.dateText);
PostText = itemView.FindViewById<TextView>(Resource.Id.postText);
LikeText = itemView.FindViewById<TextView>(Resource.Id.likeText);
CommentText = itemView.FindViewById<TextView>(Resource.Id.commentText);
RepostText = itemView.FindViewById<TextView>(Resource.Id.repostText);
ShowPopUpMenuButton = itemView.FindViewById<ImageButton>(Resource.Id.popupMenuButton);
itemView.Click += (sender, e) => listener(base.Position);
}
}
public class PostViewHodlerHeader : RecyclerView.ViewHolder
{
public TextView OwnerNameHeader{ get; private set; }
public ImageView AvatarProfileHeader { get; private set; }
public PostViewHodlerHeader(View itemView) : base(itemView)
{
OwnerNameHeader = itemView.FindViewById<TextView>(Resource.Id.details);
AvatarProfileHeader = itemView.FindViewById<ImageView>(Resource.Id.avatar_image);
}
}
}
I think problem bind with recycling elements.
Video link with problem.
How to show only one popupmenu only for current item in recyclerview? Why this problem occur?

RecyclerView don't have Item click and other events

Earlier I used ListView and there was lots of events in this class, but now I started to use RecyclerView and here I can't find any event.
for example:
RecyclerView mView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
mView.ItemClick += delegate {
// action
};
is not working with this class - RecyclerView.
Actually these events whitch I want exist in RecyclerView.Adapter so I tried this:
public class ListItemArgs : EventArgs
{
public int itemPosition;
public ListItemArgs(int pos)
{
itemPosition = pos;
}
}
public class MyAdapter : RecyclerView.Adapter
{
public event EventHandler<ListItemArgs> OnItemLongClick;
// some overrides skipped (not needed anyway)
public class MyView : RecyclerView.ViewHolder
{
public View mMainView { get; set; }
public TextView mName { get; set; }
public TextView mEventCount { get; set; }
public CheckBox mFavorite { get; set; }
public MyView(View view) : base(view)
{
mMainView = view;
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyView mHolder = holder as MyView;
mHolder.mMainView.LongClick += delegate
{
Snackbar.Make(mRecyclerView, "Ar tikrai norite trinti pasirinkimÄ…?", Snackbar.LengthLong).Show();
OnItemLongClick.Invoke(mHolder.mMainView, new ListItemArgs(position));
};
}
}
and declarations in other class:
RecyclerView mView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
RecyclerView.Adapter mAdapter new AddNewDayAdapter(mView);
And now I should be able to launch this event from mAdapter object, which leter I use to SetAdapter for my RecyclerView. (code below)
mAdapter.OnItemLongClick += (object sender, ListItemArgs e) =>
{
// action
}
mView.SetAdapter(mAdapter);
but mAdapter.OnItemLongClick is not working.
Main question: how can I get an event in which args would be view of row and selected item position ?

Xamarin passing context from OnClick event

I m a beginner in android dev, I m struggling with passing string Clicked_Message from Click event in Recycle Adapter Class to the other activity. Is it a good way to use Intent? If so how can I pass context to click event? Thanks
public class RecyclerAdapter : RecyclerView.Adapter
{
private RecyclerView mRecyclerView;
private List<NotificationClass> mEmails;
public RecyclerAdapter(List<NotificationClass> emails, RecyclerView recyclerView)
{
mEmails = emails;
mRecyclerView = recyclerView;
}
public class MyView : RecyclerView.ViewHolder
{
public View mMainView { get; set; }
public TextView mName { get; set; }
public TextView mSubject { get; set; }
public TextView mMessage { get; set; }
public MyView(View view) : base(view)
{
mMainView = view;
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View row = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.row, parent, false);
TextView txtName = row.FindViewById<TextView>(Resource.Id.txtName);
TextView txtSubject = row.FindViewById<TextView>(Resource.Id.txtSubject);
TextView txtMessage = row.FindViewById<TextView>(Resource.Id.txtMessage);
MyView view = new MyView(row) { mName = txtName, mSubject = txtSubject, mMessage = txtMessage };
return view;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyView myHolder = holder as MyView;
int indexPosition = (mEmails.Count - 1) - position;
myHolder.mMainView.Click += mMainView_Click;
myHolder.mName.Text = mEmails[position].Name;
myHolder.mSubject.Text = mEmails[position].Subject;
myHolder.mMessage.Text = mEmails[position].Message;
}
public override int ItemCount
{
get { return mEmails.Count; }
}
public void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
public void mMainView_Click(object sender, EventArgs e,Context context)
{
int position = mRecyclerView.GetChildPosition((View)sender);
int indexPosition = (mEmails.Count - 1) - position;
Console.WriteLine(mEmails[indexPosition].Message);
string Clicked_Message = (mEmails[indexPosition].Message);
var activity2 = new Intent(context, typeof(ContactActivity));
activity2.PutExtra("MyData", Clicked_Message);
context.StartActivity(activity2);
}
}
You don't need to pass a context. Just use an intent and put the information you want to pass as extras into the intent.
In case your adapter needs a context, pass it in through the constructor and store it as a field member.
This is my typical implementation of the RecyclerView.Adapter with a view holder...
public class ContactsAdapter : V7.RecyclerView.Adapter
{
private List<Contact> _contacts;
public event EventHandler ItemClick;
public void OnItemClick(ContactViewHolder holder)
{
if (ItemClick != null)
{
ItemClick(holder, EventArgs.Empty);
}
}
public ContactsAdapter(List<Contact> contacts)
: base()
{
_contacts = contacts;
}
public override void OnBindViewHolder(V7.RecyclerView.ViewHolder holder, int position)
{
var contactHolder = (ContactViewHolder)holder;
contactHolder.BindUI(_contacts[position]);
}
public override V7.RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var view = LayoutInflater.FromContext(parent.Context).Inflate(Resource.Layout.ContactsListItem, parent, false);
return new ContactViewHolder(view)
{
Adapter = this
};
}
public override int ItemCount
{
get
{
return _contacts.Count;
}
}
}
View Holder (typically in the same file as the adapter)
public class ContactViewHolder : V7.RecyclerView.ViewHolder, View.IOnClickListener
{
public TextView ContactNameTextView { get; set; }
public TextView ContactPhoneTextView { get; set; }
public TextView ContactIntialsTextView { get; set; }
public Contact Contact { get; set; }
private WeakReference _adapter;
public ContactsAdapter Adapter
{
get { return (ContactsAdapter)_adapter.Target; }
set { _adapter = new WeakReference(value); }
}
public ContactViewHolder(View view)
: base(view)
{
GetUI(view);
view.SetOnClickListener(this);
}
private void GetUI(View view)
{
ContactNameTextView = view.FindViewById<TextView>(Resource.Id.ContactName);
ContactPhoneTextView = view.FindViewById<TextView>(Resource.Id.ContactPhone);
ContactIntialsTextView = view.FindViewById<TextView>(Resource.Id.ContactInitialsTextView);
}
public void BindUI(Contact contact)
{
Contact = contact;
ContactNameTextView.Text = contact.ContactName;
ContactPhoneTextView.Text = contact.Phone1;
ContactIntialsTextView.Text = contact.Initials;
}
public void OnClick(View v)
{
Adapter.OnItemClick(this);
}
}
This encapsulates the functionality to the view holder. I also give the instance of the adapter to the view holder as a WeakReference. This allows me to call the OnItemClick, passing the instance of the view holder. If you will notice that the view holder also has an instance of the object that it is representing. This means I don't have to worry about the index that was chosen. I already have the object data available to me.
So the implementation in the Activity/Fragment is like this...
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_contacts = Contact.GetAllContacts();
_adapter = new ContactsAdapter(_contacts);
_adapter.ItemClick += ContactSelected;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.ContactsFragment, container, false);
var layoutManager = new V7.LinearLayoutManager(this.Activity) { Orientation = V7.LinearLayoutManager.Vertical };
_contactsView = view.FindViewById<V7.RecyclerView>(Resource.Id.ContactList);
_contactsView.SetAdapter(_adapter);
_contactsView.HasFixedSize = true;
_contactsView.SetLayoutManager(layoutManager);
return view;
}
private void ContactSelected (object sender, EventArgs e)
{
var holder = (ContactViewHolder)sender;
var detailFragment = new ContactDetailsFragment(holder.Contact);
MainActivity.ShowFragment(detailFragment);
}
I give the Contact to a Fragment, but you could do something similar for an activity using an intent.
Now whether this is the most efficient way of handling a click of a row in a RecyclerView, I don't know. But this implementation has been working for me.

.net DispatcherTimer fires tick event repeatedly

i have problem in my code that i don't even near to understand.
Here is my item interface;
internal interface IItem
{
void Show();
event EventHandler Completed;
TimeSpan Duration { get; set; }
string Name { get; set; }
}
internal class ItemImage : IItem
{
public TimeSpan Duration { get; set; }
public string Name { get; set; }
public event EventHandler Completed;
private DispatcherTimer _dt = new DispatcherTimer();
public void Show()
{
_dt.Interval = this.Duration;
_dt.Tick += (s, e) =>
{
_dt.Stop();
Completed(this, new EventArgs());
};
_dt.Start();
}
}
And here's my player:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
int _pIndex = 0;
List<IItem> list = new List<IItem>();
private void Button1_Click(object sender, RoutedEventArgs e)
{
list = new List<IItem>()
{
new ItemImage() { Duration = TimeSpan.FromSeconds(5), Name = "Image1" },
new ItemImage() { Duration = TimeSpan.FromSeconds(3), Name = "Image2" },
new ItemImage() { Duration = TimeSpan.FromSeconds(5), Name = "Image3" },
new ItemImage() { Duration = TimeSpan.FromSeconds(7), Name = "Image4" }
};
Next();
}
void Next()
{
var tb = new TextBlock();
tb.Text = ((IItem)list[_pIndex]).Name;
StackPanel1.Children.Add(tb);
list[_pIndex].Completed += (s, e) =>
{
Next();
};
list[_pIndex].Show();
_pIndex++;
_pIndex %= list.Count;
}
}
First list plays with no problem but on second turn DispatcherTimer doesn't wait for my duration value, and immediately fires complete event. What do i do wrong?
Thanks.
I don't know exactly what is happening (I didn't test it), but I see that every time you call Show(), another eventhandler is attached to the Tick in your ItemImage object. This could lead to some side effects you'll experiencing.
You might change it to:
internal class ItemImage : IItem
{
public TimeSpan Duration { get; set; }
public string Name { get; set; }
public event EventHandler Completed;
private DispatcherTimer _dt = new DispatcherTimer();
// constructor
public ItemImage()
{
_dt.Tick += (s, e) =>
{
_dt.Stop();
Completed(this, new EventArgs());
};
}
public void Show()
{
_dt.Interval = this.Duration;
_dt.Start();
}
}
You could recreate the DispatcherTimer or move the event attaching to the constructor. (like above)
This is also done in the Next() method with list[_pIndex].Completed. (it attaches to a class member, so every buttonclick new handlers are added to the list.)
You might reconcider the style of attaching events. Like moving them to constructors.
Like:
public partial class MainWindow : Window
{
int _pIndex = 0;
List<IItem> list = new List<IItem>();
public MainWindow()
{
InitializeComponent();
list[_pIndex].Completed += (s, e) =>
{
_pIndex++;
_pIndex %= list.Count;
Next();
};
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
list = new List<IItem>()
{
new ItemImage() { Duration = TimeSpan.FromSeconds(5), Name = "Image1" },
new ItemImage() { Duration = TimeSpan.FromSeconds(3), Name = "Image2" },
new ItemImage() { Duration = TimeSpan.FromSeconds(5), Name = "Image3" },
new ItemImage() { Duration = TimeSpan.FromSeconds(7), Name = "Image4" }
};
Next();
}
void Next()
{
var tb = new TextBlock();
tb.Text = ((IItem)list[_pIndex]).Name;
StackPanel1.Children.Add(tb);
list[_pIndex].Show();
}
}
Good luck.

Categories