我有一个用户控件,其中包含高度为100,宽度为1920的Canvas
。
在控件加载时,我会去外部源下载一个文本文件,并将TextBlock
添加到Canvas
中。然后,我想创建一个跑马灯滚动效果,这应该没有问题,但是在我将TextBlock
添加到Canvas
之后,我需要获取它们的宽度进行计算,但是ActualWidth
属性总是为零。
以下是一些代码:
private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();
public LocalNewsControl()
{
Loaded += LocalNewsControlLoaded;
}
private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
LoadDataContext();
}
private void LoadDataContext()
{
DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}
private void LoadNewsItems()
{
var viewModel = (NewsItemsViewModel)DataContext;
NewsCanvas.Children.Clear();
textBlocks.Clear();
foreach (var newsViewModel in viewModel.NewsItems)
{
var tb = new TextBlock
{
Text = newsViewModel.Headline,
FontSize = 28,
FontWeight = FontWeights.Normal,
Foreground = Brushes.Black
};
NewsCanvas.Children.Add(tb);
Canvas.SetTop(tb, 20);
Canvas.SetLeft(tb, -999);
textBlocks.AddLast(tb);
}
Dispatcher.BeginInvoke(new Action(() =>
{
var node = textBlocks.First;
while (node != null)
{
if (node.Previous != null)
{
//THIS IS WHERE ActualWidth is always ZERO
var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
Canvas.SetLeft(node.Value, left);
}
else
Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);
node = node.Next;
}
}));
}