我正在创建一个应用程序,用于测量一个人凝视约300个物体的时间。对于所有对象,它需要将时间输出到文本文件中。我已经成功地为一个对象编写了代码,但是我正在尝试为300个对象编写代码。这是我为一个对象创建的代码:
echo "\\\\\\\\"
每次在变量或元素名称中插入“ 1”时,我都希望所有300个对象都具有该值。这就是我想要的:
Stopwatch Timer = new Stopwatch();
gazeButtonControl1 = GazeInput.GetGazeElement(GazeBlock1);
gazeButtonControl1 = new GazeElement();
GazeInput.SetGazeElement(GazeBlock1, gazeButtonControl1);
TimeSpan Word1 = TimeSpan.Zero;
gazeButtonControl1.StateChanged += GazeBlockControl1_StateChanged;
void GazeBlockControl1_StateChanged(object sender, StateChangedEventArgs ea)
{
if (ea.PointerState == PointerState.Enter)
{
Timer.Start();
}
if (ea.PointerState == PointerState.Exit)
{
Timer.Stop();
Word1 += Timer.Elapsed;
File.WriteAllText(@"*insert path here", Word1.ToString());
Timer.Reset();
}
}
此代码无效。我试过使用列表,但也没有用。有谁知道如何使该解决方案有效?预先感谢!
Vincent
答案 0 :(得分:0)
您不能在变量,方法等名称中使用占位符或数组索引。
对于UWP,似乎有一个辅助方法FindChildByName
,该方法可让您通过(TypeOfChildControl)insertParentControlHere.FindChildByName("<Name of child control>")
来按其名称查找控件。
我发现以下令人困惑的代码:
gazeButtonControl1 = GazeInput.GetGazeElement(GazeBlock1);
gazeButtonControl1 = new GazeElement();
GazeInput.SetGazeElement(GazeBlock1, gazeButtonControl1);
基本上,首先从gazeButtonControl1
获取GazeBlock1
,然后忽略它以创建新的GazeElement
。我猜这是什么意思,像in this UWP Gaze sample一样,它首先检查UI控件是否具有凝视元素并且是否没有创建。所以我认为应该是:
gazeButtonControl1 = GazeInput.GetGazeElement(GazeBlock1);
if (gazeButtonControl1 == null)
{
gazeButtonControl1 = new GazeElement();
GazeInput.SetGazeElement(GazeBlock1, gazeButtonControl1);
}
就像我在最初的评论中所写的那样,您可能需要为每个凝视元素单独设置一个计时器。
所以总的来说应该是这样(尽管未经测试):
public class YourClass
{
private TimeSpan[] Word = new TimeSpan[300];
private Stopwatch[] Timer = new Stopwatch[300];
private GazeElement[] gazeButtonControl = new GazeElement[300];
public YourMethod(...)
{
for (int i = 0; i < 300; i++)
{
// first find gaze block where parentControl is the control containing your gaze blocks.
var gazeBlock = (UIElement)parentControl.FindChildByName("GazeBlock" + (i + 1));
gazeButtonControl[i] = GazeInput.GetGazeElement(gazeBlock);
if (gazeButtonControl[i] == null)
{
gazeButtonControl[i] = new GazeElement();
GazeInput.SetGazeElement(gazeBlock, gazeButtonControl[i]);
}
Word[i] = TimeSpan.Zero;
Timer[i] = new Stopwatch();
gazeButtonControl[i].StateChanged += GazeBlockControl_StateChanged;
}
}
private void GazeBlockControl_StateChanged(object sender, StateChangedEventArgs ea)
{
// get the GazeElement for which this event was raised
var changedControl = (GazeElement)sender;
// find its index in your list of GazeElements.
var i = Array.IndexOf(gazeButtonControl, changedControl);
if (ea.PointerState == PointerState.Enter)
{
Timer[i].Start();
}
if (ea.PointerState == PointerState.Exit)
{
Timer[i].Stop();
Word[i] += Timer.Elapsed;
File.WriteAllText(@"*insert path here", Word[i].ToString());
Timer[i].Reset();
}
}
}
请不要因为我将gazeButtonControl声明为数组而使用Array.IndexOf
而不是gazeButtonControl.IndexOf
。如果它是列表(例如List<GazeElement> gazeButtonControl
),则可以使用gazeButtonControl.IndexOf
。