我的代码中有问题,我什至无法理解。
这是我的物品界面;
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();
}
}
这是我的播放器:
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;
}
}
第一个列表播放没有问题,但在第二轮 DispatcherTimer 不等待我的持续时间值,并立即触发完成事件。我做错了什么?谢谢。