C# 在stackpanel中定位动态项目
我对这种编码有点陌生,但我正在尝试访问C# 在stackpanel中定位动态项目,c#,silverlight,windows-phone-7,xaml,windows-8,C#,Silverlight,Windows Phone 7,Xaml,Windows 8,我对这种编码有点陌生,但我正在尝试访问StackPanel中动态创建的TextBlock属性(如TextBlock.Tag、Name等)。我打算对每个TextBlock执行的操作是查看其标记属性是什么,如果它与条件匹配,计时器将以某种方式更改TextBlock属性 因此,找到一种方法来编码每个计时器的刻度:“对于StackPanel中的每个TextBlock.Tag,如果TextBlock.Tag==this,则对TextBlock执行此操作。” 下面是一些代码,可以帮助您直观地了解我在做什么:
StackPanel
中动态创建的TextBlock
属性(如TextBlock.Tag、Name等)。我打算对每个TextBlock
执行的操作是查看其标记
属性是什么,如果它与条件匹配,计时器将以某种方式更改TextBlock
属性
因此,找到一种方法来编码每个计时器的刻度:“对于StackPanel中的每个TextBlock.Tag
,如果TextBlock.Tag==this
,则对TextBlock
执行此操作。”
下面是一些代码,可以帮助您直观地了解我在做什么:
Xaml代码:
<StackPanel Name="StackP" Margin="6,0,6,0"/>
{
for (var i = 0; i < MaxCountOfResults; ++i)
{
TextBlock SingleResult= new TextBlock { Text = Resultname.ToString(), FontSize = 20, Margin = new Thickness(30, -39, 0, 0) };
//a condition to alter certain TextBlock properties.
if (i == .... (irrelevant to this example))
{
SingleResult.Foreground = new SolidColorBrush(Colors.Yellow);
SingleResult.Tag = "00001";
}
//Add this dynamic TextBlock to the StackPanel StackP
StackP.Children.Add(SingleResult);
}
//the timer that starts when this entire function of adding the TextBlocks to the StackPanel StackP tree is done.
Atimer = new Timer(new TimerCallback(Atimer_tick), 0, 0, 100);
}
public void Atimer_tick(object state)
{
The area where I have no idea how to reference the Children of stackpanel StackP with every timer tick. I need help :(
}
C#代码:
<StackPanel Name="StackP" Margin="6,0,6,0"/>
{
for (var i = 0; i < MaxCountOfResults; ++i)
{
TextBlock SingleResult= new TextBlock { Text = Resultname.ToString(), FontSize = 20, Margin = new Thickness(30, -39, 0, 0) };
//a condition to alter certain TextBlock properties.
if (i == .... (irrelevant to this example))
{
SingleResult.Foreground = new SolidColorBrush(Colors.Yellow);
SingleResult.Tag = "00001";
}
//Add this dynamic TextBlock to the StackPanel StackP
StackP.Children.Add(SingleResult);
}
//the timer that starts when this entire function of adding the TextBlocks to the StackPanel StackP tree is done.
Atimer = new Timer(new TimerCallback(Atimer_tick), 0, 0, 100);
}
public void Atimer_tick(object state)
{
The area where I have no idea how to reference the Children of stackpanel StackP with every timer tick. I need help :(
}
{
对于(变量i=0;i
谢谢大家。我仍在学习这一点,需要帮助。您应该能够使用计时器,但我建议使用
BackgroundWorker
执行循环,而不是计时器事件,这可能会发生冲突。更好的是,使用带触发器的SilverLight样式的动画
在非UI线程上,您希望使用Dispatcher调用在UI线程上调用异步代码,类似于:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
foreach (TextBlock txb in StackP.Children){
txb.Text = "xyz";
}
}
catch (Exception ex)
{
Debug.WriteLine("error: "+ex);
}
});
谢谢你,因为这正是我要找的。然而,奇怪的是,我在foreach行上得到了一个InvalidCastException。我明天会看一看,因为我现在太累了,走不动了:/。@shaundty这意味着你的stackpanel中除了文本块之外还有其他东西。在你的foreach中使用
of type
来过滤它们:foreach(StackP.Children.OfType()中的变量txb)