带有 xml 事件的按钮的动态列表
我正在开发 silverlight RSS 阅读器作为学校项目,但有一个问题。 我想在 xml 中定义 feed 源列表,并将此 xml 加载到按钮列表,每个按钮对应一个 feed。 xml 看起来
<FeedList>
<Feed ButtonContent="HDRip's on RlsLog.net" Url="http://www.rlslog.net/category/movies/hdrip/feed/" />
</FeedList>
我正在使用 linq 加载此 xml,并且创建按钮
XDocument xdoc = XDocument.Load(string.Format("feeds.xml"));
if (xdoc != null)
{
var feedlist =
(from l in xdoc.Descendants("Feed")
select new MyButtons
{
Content = l.Attribute("ButtonContent").Value,
FeedUrl = l.Attribute("Url").Value
}
).ToList();
foreach (MyButtons feedbutton in feedlist)
{
Button b1 = new Button();
b1.Content = feedbutton.Content;
b1.Click += (s, e) => { feedViewer.LoadFeed(feedbutton.FeedUrl); };
ButtonPanel.Children.Add(b1);
}
}
按钮内容加载正常,但该 feed url 对于所有按钮都使用 xml 中的最后一个。你能告诉我我做错了什么吗?
I'm working on silverlight rss reader as schoolproject and I have one problem.
I want to define list of feed sources in xml and load this xml to list of button, each button for one feed.
xml looks like
<FeedList>
<Feed ButtonContent="HDRip's on RlsLog.net" Url="http://www.rlslog.net/category/movies/hdrip/feed/" />
</FeedList>
I'm loading this xml using linq and creating button
XDocument xdoc = XDocument.Load(string.Format("feeds.xml"));
if (xdoc != null)
{
var feedlist =
(from l in xdoc.Descendants("Feed")
select new MyButtons
{
Content = l.Attribute("ButtonContent").Value,
FeedUrl = l.Attribute("Url").Value
}
).ToList();
foreach (MyButtons feedbutton in feedlist)
{
Button b1 = new Button();
b1.Content = feedbutton.Content;
b1.Click += (s, e) => { feedViewer.LoadFeed(feedbutton.FeedUrl); };
ButtonPanel.Children.Add(b1);
}
}
button content is loading fine but that feed url is used the last one in xml for all buttons. could you please advice me what i'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来
feedbutton
被捕获为迭代变量,从而导致您在使用 lambda 表达式分配事件处理程序时所描述的行为。试试这个:
Eric Lippert 在博客中讨论了此主题:
It looks like
feedbutton
is being captured as an iteration variable, thus causing the behavior you're describing when you assign the event handler with the lambda expression.Try this instead:
Eric Lippert has blogged about this topic: