我有一个用户控件,其Canvas
高度为 100,宽度为 1920。
在加载控件时,我转到外部源,下载一个文本文件并将TextBlock
s 添加到 Canvas。然后我想创建一个应该可以正常工作的选框滚动效果,除了将TextBlock
s 添加到之后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;
}
}));
}