C#用于TextBlocks数组的Eventhandler [英] C# Eventhandler for array of TextBlocks
本文介绍了C#用于TextBlocks数组的Eventhandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为一个TextBlocks数组添加可用的事件处理程序,但似乎它总是sHeadline [x]的最后一个元素来获取事件处理程序。例如,如果我有sHeadline [x]的10个元素,则总是sHeadline [9]获取事件处理程序。
如何解决此问题?
谢谢!
I am trying to add mutible eventhandlers for a array of TextBlocks, but it seems like it is always the last element of sHeadline[x] that gets the eventhandler. For example if I have 10 elements of sHeadline[x] it is always sHeadline[9] that gets the eventhandler.
How can I fix this?
Thanks!
void service_GetSearchForVesselCompleted(object sender, PositionServiceReference.GetSearchForVesselCompletedEventArgs e)
{
// Number of results
var numberOfResults = e.Result.Count;
// Variables
String vesselName;
SolidColorBrush textColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 30, 30, 30));
// Create headlines
TextBlock[] sHeadline = new TextBlock[numberOfResults];
// Go trough results list
for (int x = 0; x < numberOfResults; x++)
{
// Get vales
vesselName = e.Result[x].Vessel_Name;
sHeadline[x] = new TextBlock();
sHeadline[x].TextDecorations = TextDecorations.Underline;
sHeadline[x].FontSize = 12;
sHeadline[x].Text = vesselName;
sHeadline[x].Margin = new Thickness(9, 0, 0, 0);
sHeadline[x].Height = 15;
stackPanelSearchResults.Children.Add(sHeadline[x]);
// Add listners
sHeadline[x].MouseLeftButtonDown += new MouseButtonEventHandler((object senderH, MouseButtonEventArgs eH) => sHeadline_MouseLeftButtonDown(senderH, eH, vesselName, x));
}
}
void sHeadline_MouseLeftButtonDown(object sender, MouseButtonEventArgs e, string inpVesselName, int x)
{
labelStatus.Content = "Click on " + inpVesselName + " " + x;
}
推荐答案
这类答案回答同样的问题:
http://stackoverflow.com / questions / 4155691 / c-sharp-lambda-local-variable-value-not-take-when-you-think [ ^ ]
但基本上你没有在创建lambda时存储vesselname和x的值,而是自己的catual变量,因此它们会被所有这些处理程序的最后一个值所困。
This sort of answers the same question:
http://stackoverflow.com/questions/4155691/c-sharp-lambda-local-variable-value-not-taken-when-you-think[^]
but basically you are not storing the value of vesselname and x when you create the lambda but the catual variable themselves so they get stuck on their last value for all of those handlers.
这篇关于C#用于TextBlocks数组的Eventhandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文